How to use channelId method in Playwright Internal

Best JavaScript code snippet using playwright-internal

main.test.js

Source:main.test.js Github

copy

Full Screen

1import request from 'supertest';2import server from '../src/server';3import { reset } from '../src/service';4const IMAGE = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';5const INVALID_TOKEN = 'Emily';6const USER1 = {7 name: 'Betty',8 email: 'betty@email.com',9 password: 'cardigan',10 bio: 'when you are young they assume you know nothing',11};12const USER2 = {13 name: 'Augustine',14 email: 'augustine@email.com',15 password: 'august',16 bio: 'i can see us lost in the memory, august slipped away into a moment in time',17};18const USER3 = {19 name: 'James',20 email: 'james@email.com',21 password: 'betty',22 bio: 'if i just showed up at your party, would you have me?',23};24const CHANNEL_PUBLIC = {25 name: 'Inez\'s public rumour forum',26 name2: 'Inez\'s public rumour forum!',27 description: 'you heard the rumours from Inez, you can\'t believe a word she says',28 description2: 'moo',29 private: false,30};31const CHANNEL_PRIVATE = {32 name: 'Inez\'s private rumour mill',33 name2: 'Inez\'s private rumour mill!',34 description: 'you can\'t believe a word she says most times, but this time it was true',35 description2: 'baa',36 private: true,37};38const postTry = async (path, status, payload, token) => sendTry('post', path, status, payload, token);39const getTry = async (path, status, payload, token) => sendTry('get', path, status, payload, token);40const deleteTry = async (path, status, payload, token) => sendTry('delete', path, status, payload, token);41const putTry = async (path, status, payload, token) => sendTry('put', path, status, payload, token);42const sendTry = async (typeFn, path, status = 200, payload = {}, token = null) => {43 let req = request(server);44 if (typeFn === 'post') {45 req = req.post(path);46 } else if (typeFn === 'get') {47 req = req.get(path);48 } else if (typeFn === 'delete') {49 req = req.delete(path);50 } else if (typeFn === 'put') {51 req = req.put(path);52 }53 if (token !== null) {54 req = req.set('Authorization', `Bearer ${token}`);55 }56 const response = await req.send(payload);57 expect(response.statusCode).toBe(status);58 return response.body;59};60const validToken = async (user) => {61 const { token } = await postTry('/auth/login', 200, {62 email: user.email,63 password: user.password,64 });65 return token;66}67const publicChannelId = async () => {68 const { channels } = await getTry('/channel', 200, {}, await validToken(USER1));69 return channels[0].private ? channels[1].id : channels[0].id;70};71const privateChannelId = async () => {72 const { channels } = await getTry('/channel', 200, {}, await validToken(USER1));73 return channels[0].private ? channels[0].id : channels[1].id;74};75const getUserId = async (user) => {76 const { users, } = await getTry('/user', 200, {}, await validToken(USER1));77 return users.find(u => u.email === user.email).id;78}79describe('Auth tests', () => {80 beforeAll(() => {81 reset();82 });83 beforeAll(() => {84 server.close();85 });86 test('Registration of initial user', async () => {87 const { token, userId, } = await postTry('/auth/register', 200, {88 email: USER1.email,89 password: USER1.password,90 name: USER1.name,91 });92 expect(token instanceof String);93 expect(userId).toBe(await getUserId(USER1));94 });95 test('Inability to re-register a user', async () => {96 await postTry('/auth/register', 400, {97 email: USER1.email,98 password: USER1.password,99 name: USER1.name,100 });101 });102 test('Registration of second user', async () => {103 const { token, } = await postTry('/auth/register', 200, {104 email: USER2.email,105 password: USER2.password,106 name: USER2.name,107 });108 expect(token instanceof String);109 });110 test('Login to an existing user', async () => {111 const { token, userId, } = await postTry('/auth/login', 200, {112 email: USER1.email,113 password: USER1.password,114 });115 expect(token instanceof String);116 expect(userId).toBe(await getUserId(USER1));117 });118 test('Login attempt with invalid credentials 1', async () => {119 await postTry('/auth/login', 400, {120 email: 'inez@email.com',121 password: USER1.password,122 });123 });124 test('Login attempt with invalid credentials 2', async () => {125 await postTry('/auth/login', 400, {126 email: USER1.email,127 password: 'car again',128 });129 });130 test('Logout a valid session', async () => {131 const body = await postTry('/auth/logout', 200, {}, await validToken(USER1));132 expect(body).toMatchObject({});133 });134 test('Logout a session without auth token', async () => {135 const body = await postTry('/auth/logout', 403, {});136 expect(body).toMatchObject({});137 });138});139describe('Channel tests', () => {140 beforeAll(async () => {141 reset();142 await postTry('/auth/register', 200, {143 email: USER1.email,144 password: USER1.password,145 name: USER1.name,146 });147 await postTry('/auth/register', 200, {148 email: USER2.email,149 password: USER2.password,150 name: USER2.name,151 });152 await postTry('/auth/register', 200, {153 email: USER3.email,154 password: USER3.password,155 name: USER3.name,156 });157 });158 beforeAll(() => {159 server.close();160 });161 test('Viewing channels, invalid token', async () => {162 await getTry('/channel', 403, {}, INVALID_TOKEN);163 });164 test('Initially there are no channels', async () => {165 const { channels, } = await getTry('/channel', 200, {}, await validToken(USER1));166 expect(channels).toHaveLength(0);167 });168 test('Creating a single channel, token missing', async () => {169 await postTry('/channel', 403, {170 name: CHANNEL_PUBLIC.name,171 private: CHANNEL_PUBLIC.private,172 description: CHANNEL_PUBLIC.description,173 });174 });175 test('Creating a single channel, invalid token', async () => {176 await postTry('/channel', 403, {177 name: CHANNEL_PUBLIC.name,178 private: CHANNEL_PUBLIC.private,179 description: CHANNEL_PUBLIC.description,180 }, INVALID_TOKEN);181 });182 test('Creating a single channel, all values missing', async () => {183 await postTry('/channel', 400, {}, await validToken(USER1));184 });185 test('Creating a single channel, name missing', async () => {186 await postTry('/channel', 400, {187 private: CHANNEL_PUBLIC.private,188 description: CHANNEL_PUBLIC.description,189 }, await validToken(USER1));190 });191 test('Creating a single channel, public setting missing', async () => {192 await postTry('/channel', 400, {193 name: CHANNEL_PUBLIC.name,194 description: CHANNEL_PUBLIC.description,195 }, await validToken(USER1));196 });197 test('Creating a single channel, description missing', async () => {198 await postTry('/channel', 400, {199 name: CHANNEL_PUBLIC.name,200 private: CHANNEL_PUBLIC.private,201 }, await validToken(USER1));202 });203 test('Creating a single public channel', async () => {204 await postTry('/channel', 200, {205 name: CHANNEL_PUBLIC.name,206 private: CHANNEL_PUBLIC.private,207 description: CHANNEL_PUBLIC.description,208 }, await validToken(USER1));209 });210 test('That there is now one channel', async () => {211 const { channels, } = await getTry('/channel', 200, {}, await validToken(USER1));212 expect(channels).toHaveLength(1);213 expect(typeof channels[0].id).toBe('number');214 expect(channels[0].name).toBe(CHANNEL_PUBLIC.name);215 expect(typeof channels[0].creator).toBe('number');216 expect(channels[0].private).toBe(CHANNEL_PUBLIC.private);217 expect(channels[0].members).toMatchObject([channels[0].creator]);218 });219 test('That the one channel\'s details can be viewed', async () => {220 const channelId = await publicChannelId();221 const channel = await getTry(`/channel/${channelId}`, 200, {}, await validToken(USER1));222 expect(channel.name).toBe(CHANNEL_PUBLIC.name);223 expect(typeof channel.creator).toBe('number');224 expect(channel.private).toBe(CHANNEL_PUBLIC.private);225 expect(channel.description).toBe(CHANNEL_PUBLIC.description);226 expect(typeof channel.createdAt).toBe('string');227 expect(channel.members).toMatchObject([channel.creator]);228 });229 test('Viewing one channel\'s details, invalid token', async () => {230 const channelId = await publicChannelId();231 await getTry(`/channel/${channelId}`, 403, {}, INVALID_TOKEN);232 });233 test('Viewing one channel\'s details, invalid channelId', async () => {234 await getTry('/channel/999999999', 400, {}, await validToken(USER1));235 });236 test('Viewing one channel\'s details, user not a member', async () => {237 const channelId = await publicChannelId();238 await getTry(`/channel/${channelId}`, 403, {}, await validToken(USER2));239 });240 test('Create a second private channel', async () => {241 await postTry('/channel', 200, {242 name: CHANNEL_PRIVATE.name,243 private: CHANNEL_PRIVATE.private,244 description: CHANNEL_PRIVATE.description,245 }, await validToken(USER1));246 });247 test('That there are now two channels', async () => {248 const { channels, } = await getTry('/channel', 200, {}, await validToken(USER1));249 expect(channels).toHaveLength(2);250 expect(channels[0].id !== channels[1].id)251 });252 test('First user can\'t join invalid channel', async () => {253 await postTry('/channel/999999999/join', 400, {}, await validToken(USER1));254 });255 test('First user can\'t join channels they\'re already in', async () => {256 const channelIdPublic = await publicChannelId();257 const channelIdPrivate = await privateChannelId();258 await postTry(`/channel/${channelIdPublic}/join`, 400, {}, await validToken(USER1));259 await postTry(`/channel/${channelIdPrivate}/join`, 400, {}, await validToken(USER1));260 });261 test('Second user can join public channel', async () => {262 const channelId = await publicChannelId();263 await postTry(`/channel/${channelId}/join`, 200, {}, await validToken(USER2));264 });265 test('Second user can now view channel details', async () => {266 const channelId = await publicChannelId();267 const channel = await getTry(`/channel/${channelId}`, 200, {}, await validToken(USER2));268 expect(channel.name).toBe(CHANNEL_PUBLIC.name);269 expect(typeof channel.creator).toBe('number');270 expect(channel.private).toBe(CHANNEL_PUBLIC.private);271 expect(channel.description).toBe(CHANNEL_PUBLIC.description);272 expect(typeof channel.createdAt).toBe('string');273 expect(channel.members).toHaveLength(2);274 });275 test('Second user can\'t join private channel', async () => {276 const channelId = await privateChannelId();277 await postTry(`/channel/${channelId}/join`, 403, {}, await validToken(USER2));278 });279 test('Invalid token can\'t join public channel', async () => {280 const channelId = await publicChannelId();281 await postTry(`/channel/${channelId}/join`, 403, {}, INVALID_TOKEN);282 });283 test('Invalid token can\'t join private channel', async () => {284 const channelId = await privateChannelId();285 await postTry(`/channel/${channelId}/join`, 403, {}, INVALID_TOKEN);286 });287 test('Second user can leave public channel', async () => {288 const channelId = await publicChannelId();289 await postTry(`/channel/${channelId}/leave`, 200, {}, await validToken(USER2));290 });291 test('Second user can\'t leave channel they aren\'t in', async () => {292 const channelId = await publicChannelId();293 await postTry(`/channel/${channelId}/leave`, 403, {}, await validToken(USER2));294 });295 test('Invalid token can\'t leave channel', async () => {296 const channelId = await publicChannelId();297 await postTry(`/channel/${channelId}/leave`, 403, {}, INVALID_TOKEN);298 });299 test('First user can\'t leave invalid channel', async () => {300 await postTry('/channel/999999999/leave', 400, {}, await validToken(USER1));301 });302 test('Second user can\'t update channel they aren\'t in', async () => {303 const channelId = await publicChannelId();304 await putTry(`/channel/${channelId}`, 403, {}, await validToken(USER2));305 });306 test('Invalid token can\'t update channel', async () => {307 const channelId = await publicChannelId();308 await putTry(`/channel/${channelId}`, 403, {}, INVALID_TOKEN);309 });310 test('First user can\'t update invalid channel', async () => {311 await putTry('/channel/999999999', 400, {}, await validToken(USER1));312 });313 test('Can update channel details with nothing new', async () => {314 const channelId = await publicChannelId();315 await putTry(`/channel/${channelId}`, 200, {}, await validToken(USER1));316 });317 test('First user can update public channel details', async () => {318 const channelId = await publicChannelId();319 await putTry(`/channel/${channelId}`, 200, {320 name: CHANNEL_PUBLIC.name2,321 description: CHANNEL_PUBLIC.description2,322 }, await validToken(USER1));323 });324 test('Updates were applied', async () => {325 const channelId = await publicChannelId();326 const channel = await getTry(`/channel/${channelId}`, 200, {}, await validToken(USER1));327 expect(channel.name).toBe(CHANNEL_PUBLIC.name2);328 expect(typeof channel.creator).toBe('number');329 expect(channel.private).toBe(CHANNEL_PUBLIC.private);330 expect(channel.description).toBe(CHANNEL_PUBLIC.description2);331 expect(typeof channel.createdAt).toBe('string');332 expect(channel.members).toMatchObject([channel.creator]);333 });334 test('First user can update private channel details', async () => {335 const channelId = await privateChannelId();336 await putTry(`/channel/${channelId}`, 200, {337 name: CHANNEL_PRIVATE.name2,338 description: CHANNEL_PRIVATE.description2,339 }, await validToken(USER1));340 });341 test('Updates were applied #2', async () => {342 const channelId = await privateChannelId();343 const channel = await getTry(`/channel/${channelId}`, 200, {}, await validToken(USER1));344 expect(channel.name).toBe(CHANNEL_PRIVATE.name2);345 expect(typeof channel.creator).toBe('number');346 expect(channel.private).toBe(CHANNEL_PRIVATE.private);347 expect(channel.description).toBe(CHANNEL_PRIVATE.description2);348 expect(typeof channel.createdAt).toBe('string');349 expect(channel.members).toMatchObject([channel.creator]);350 });351 test('Invalid user can\'t invite user to public channel', async () => {352 const channelId = await publicChannelId();353 await postTry(`/channel/${channelId}/invite`, 403, {354 userId: await getUserId(USER3),355 }, INVALID_TOKEN);356 });357 test('User can\'t invite invalid user to public channel', async () => {358 const channelId = await publicChannelId();359 await postTry(`/channel/${channelId}/invite`, 400, {360 userId: 999999999,361 }, await validToken(USER1));362 });363 test('User can\'t invite other user to invalid channel', async () => {364 await postTry('/channel/999999999/invite', 400, {365 userId: await getUserId(USER2),366 }, await validToken(USER1));367 });368 test('Non-member can\'t invite user to public channel', async () => {369 const channelId = await publicChannelId();370 await postTry(`/channel/${channelId}/invite`, 403, {371 userId: await getUserId(USER3),372 }, await validToken(USER2));373 });374 test('Non-member can\'t invite self to public channel', async () => {375 const channelId = await publicChannelId();376 await postTry(`/channel/${channelId}/invite`, 403, {377 userId: await getUserId(USER3),378 }, await validToken(USER3));379 });380 test('Creator can invite second user to public channel', async () => {381 const channelId = await publicChannelId();382 await postTry(`/channel/${channelId}/invite`, 200, {383 userId: await getUserId(USER2),384 }, await validToken(USER1));385 const channel = await getTry(`/channel/${channelId}`, 200, {}, await validToken(USER2));386 expect(channel.members).toHaveLength(2);387 });388 test('Can\'t invite user who is already a member', async () => {389 const channelId = await publicChannelId();390 await postTry(`/channel/${channelId}/invite`, 400, {391 userId: await getUserId(USER2),392 }, await validToken(USER1));393 });394 test('Second user (member) can invite third user to public channel', async () => {395 const channelId = await publicChannelId();396 await postTry(`/channel/${channelId}/invite`, 200, {397 userId: await getUserId(USER3),398 }, await validToken(USER2));399 const channel = await getTry(`/channel/${channelId}`, 200, {}, await validToken(USER3));400 expect(channel.members).toHaveLength(3);401 });402 test('Creator can invite second user to private channel', async () => {403 const channelId = await privateChannelId();404 await postTry(`/channel/${channelId}/invite`, 200, {405 userId: await getUserId(USER2),406 }, await validToken(USER1));407 const channel = await getTry(`/channel/${channelId}`, 200, {}, await validToken(USER2));408 expect(channel.members).toHaveLength(2);409 });410});411describe('User tests', () => {412 beforeAll(async () => {413 reset();414 await postTry('/auth/register', 200, {415 email: USER1.email,416 password: USER1.password,417 name: USER1.name,418 });419 await postTry('/auth/register', 200, {420 email: USER2.email,421 password: USER2.password,422 name: USER2.name,423 });424 });425 beforeAll(() => {426 server.close();427 });428 test('Viewing users, invalid token', async () => {429 await getTry('/user', 403, {}, INVALID_TOKEN);430 });431 test('Both users can view all users', async () => {432 let { users, } = await getTry('/user', 200, {}, await validToken(USER1));433 expect(users).toHaveLength(2);434 ({ users, } = await getTry('/user', 200, {}, await validToken(USER2)));435 expect(users).toHaveLength(2);436 });437 test('First user can view own profile', async () => {438 const profile = await getTry(`/user/${await getUserId(USER1)}`, 200, {}, await validToken(USER1));439 expect(profile.name).toBe(USER1.name);440 expect(profile.bio).toBe(null);441 });442 test('First user can view second user\'s profile', async () => {443 const profile = await getTry(`/user/${await getUserId(USER2)}`, 200, {}, await validToken(USER1));444 expect(profile.name).toBe(USER2.name);445 expect(profile.bio).toBe(null);446 });447 test('Second user can view first user\'s profile', async () => {448 const profile = await getTry(`/user/${await getUserId(USER1)}`, 200, {}, await validToken(USER2));449 expect(profile.name).toBe(USER1.name);450 expect(profile.bio).toBe(null);451 });452 test('Invalid token can\'t view other user\'s profiles', async () => {453 await getTry(`/user/${await getUserId(USER1)}`, 403, {}, INVALID_TOKEN);454 });455 test('Can\'t view invalid user\'s profiles', async () => {456 await getTry('/user/99999999', 400, {}, await validToken(USER1));457 });458 test('First user can update own profile', async () => {459 await putTry('/user', 200, {460 bio: USER1.bio,461 image: IMAGE,462 }, await validToken(USER1));463 });464 test('Updates applied', async () => {465 const profile = await getTry(`/user/${await getUserId(USER1)}`, 200, {}, await validToken(USER1));466 expect(profile.name).toBe(USER1.name);467 expect(profile.bio).toBe(USER1.bio);468 expect(profile.image).toBe(IMAGE);469 });470 test('Invalid user can\'t update own profile', async () => {471 await putTry('/user', 403, {472 bio: USER1.bio,473 }, INVALID_TOKEN);474 });475 test('Can\'t reuse email', async () => {476 await putTry('/user', 400, {477 email: USER2.email,478 }, await validToken(USER1));479 });480 test('Can update nothing', async () => {481 await putTry('/user', 200, {}, await validToken(USER1));482 });483 test('Can change everything in profile', async () => {484 await putTry('/user', 200, {485 email: USER3.email,486 password: USER3.password,487 name: USER3.name,488 bio: USER3.bio,489 }, await validToken(USER2));490 });491 test('Updates applied', async () => {492 const profile = await getTry(`/user/${await getUserId(USER3)}`, 200, {}, await validToken(USER1));493 expect(profile.name).toBe(USER3.name);494 expect(profile.bio).toBe(USER3.bio);495 });496 test('Check if can log in with new credentials and revert profile', async () => {497 await putTry('/user', 200, {498 email: USER2.email,499 password: USER2.password,500 name: USER2.name,501 bio: USER2.bio,502 }, await validToken(USER3));503 });504 test('Updating with used email won\'t work but other fields will still update', async () => {505 await putTry('/user', 400, {506 email: USER1.email,507 name: USER3.name,508 bio: USER3.bio,509 }, await validToken(USER2));510 const profile = await getTry(`/user/${await getUserId(USER2)}`, 200, {}, await validToken(USER1));511 expect(profile.email).toBe(USER2.email);512 expect(profile.name).toBe(USER3.name);513 expect(profile.bio).toBe(USER3.bio);514 });515});516describe('Message tests', () => {517 beforeAll(async () => {518 reset();519 await postTry('/auth/register', 200, {520 email: USER1.email,521 password: USER1.password,522 name: USER1.name,523 });524 await postTry('/auth/register', 200, {525 email: USER2.email,526 password: USER2.password,527 name: USER2.name,528 });529 await postTry('/channel', 200, {530 name: CHANNEL_PUBLIC.name,531 private: CHANNEL_PUBLIC.private,532 description: CHANNEL_PUBLIC.description,533 }, await validToken(USER1));534 await postTry('/channel', 200, {535 name: CHANNEL_PRIVATE.name,536 private: CHANNEL_PRIVATE.private,537 description: CHANNEL_PRIVATE.description,538 }, await validToken(USER1));539 });540 beforeAll(() => {541 server.close();542 });543 test('Viewing messages, invalid token', async () => {544 const channelId = await publicChannelId();545 await getTry(`/message/${channelId}?start=0`, 403, {}, INVALID_TOKEN);546 });547 test('Viewing messages, invalid channel ID', async () => {548 await getTry('/message/999999999?start=0', 400, {}, await validToken(USER1));549 });550 test('Viewing public messages, not member', async () => {551 const channelId = await publicChannelId();552 await getTry(`/message/${channelId}?start=0`, 403, {}, await validToken(USER2));553 });554 test('Viewing private messages, not member', async () => {555 const channelId = await privateChannelId();556 await getTry(`/message/${channelId}?start=0`, 403, {}, await validToken(USER2));557 });558 test('Viewing public messages, no start value', async () => {559 const channelId = await publicChannelId();560 await getTry(`/message/${channelId}`, 400, {}, await validToken(USER2));561 });562 test('Viewing public messages, negative start value', async () => {563 const channelId = await publicChannelId();564 await getTry(`/message/${channelId}?start=-2`, 400, {}, await validToken(USER2));565 });566 test('Viewing public messages, should succeed but have no messages', async () => {567 const channelId = await publicChannelId();568 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));569 expect(messages).toHaveLength(0);570 });571 test('Sending message, invalid token', async () => {572 const channelId = await publicChannelId();573 await postTry(`/message/${channelId}`, 403, {574 message: 'message',575 image: IMAGE,576 }, INVALID_TOKEN);577 });578 test('Sending message, invalid channel ID', async () => {579 await postTry('/message/999999999', 400, {580 message: 'message',581 image: IMAGE,582 }, await validToken(USER1));583 });584 test('Sending public message, not member', async () => {585 const channelId = await publicChannelId();586 await postTry(`/message/${channelId}`, 403, {587 message: 'message',588 image: IMAGE,589 }, await validToken(USER2));590 });591 test('Sending private message, not member', async () => {592 const channelId = await privateChannelId();593 await postTry(`/message/${channelId}`, 403, {594 message: 'message',595 image: IMAGE,596 }, await validToken(USER2));597 });598 test('Sending message, no message or image', async () => {599 const channelId = await publicChannelId();600 await postTry(`/message/${channelId}`, 400, {}, await validToken(USER1));601 });602 test('Sending messages, messages or images not strings', async () => {603 const channelId = await publicChannelId();604 await postTry(`/message/${channelId}`, 400, {605 message: 123,606 image: IMAGE,607 }, await validToken(USER1));608 await postTry(`/message/${channelId}`, 400, {609 message: 'if i can\'t have love i want power',610 image: true,611 }, await validToken(USER1));612 });613 test('Sending message', async () => {614 const channelId = await publicChannelId();615 await postTry(`/message/${channelId}`, 200, {616 message: 'message1',617 }, await validToken(USER1));618 });619 test('Viewing messages, there should be one message', async () => {620 const channelId = await publicChannelId();621 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));622 expect(messages).toHaveLength(1);623 expect(typeof messages[0].id).toBe('number');624 expect(messages[0].message).toBe('message1');625 expect(messages[0].image).toBe(undefined);626 expect(messages[0].sender).toBe(await getUserId(USER1));627 expect(typeof messages[0].sentAt).toBe('string');628 expect(messages[0].edited).toBe(false);629 expect(messages[0].editedAt).toBe(null);630 expect(messages[0].pinned).toBe(false);631 expect(messages[0].reacts).toMatchObject([]);632 });633 test('Viewing messages with start value 1, should be empty', async () => {634 const channelId = await publicChannelId();635 const { messages, } = await getTry(`/message/${channelId}?start=1`, 200, {}, await validToken(USER1));636 expect(messages).toHaveLength(0);637 });638 test('Sending 25 more messages', async () => {639 const channelId = await publicChannelId();640 for (let i = 2; i < 27; i += 1) {641 await postTry(`/message/${channelId}`, 200, {642 message: `message${i}`,643 }, await validToken(USER1));644 }645 });646 test('Viewing messages, there should be 25 message (pagination) in the correct order', async () => {647 const channelId = await publicChannelId();648 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));649 expect(messages).toHaveLength(25);650 expect(messages[0].message).toBe('message26');651 expect(messages[24].message).toBe('message2');652 });653 test('Viewing messages with start value 25', async () => {654 const channelId = await publicChannelId();655 const { messages, } = await getTry(`/message/${channelId}?start=25`, 200, {}, await validToken(USER1));656 expect(messages).toHaveLength(1);657 expect(messages[0].message).toBe('message1');658 });659 test('Sending image', async () => {660 const channelId = await publicChannelId();661 await postTry(`/message/${channelId}`, 200, {662 image: IMAGE,663 }, await validToken(USER1));664 });665 test('Check if image was sent', async () => {666 const channelId = await publicChannelId();667 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));668 expect(typeof messages[0].id).toBe('number');669 expect(messages[0].message).toBe(undefined);670 expect(messages[0].image).toBe(IMAGE);671 expect(messages[0].sender).toBe(await getUserId(USER1));672 expect(typeof messages[0].sentAt).toBe('string');673 expect(messages[0].edited).toBe(false);674 expect(messages[0].editedAt).toBe(null);675 expect(messages[0].pinned).toBe(false);676 expect(messages[0].reacts).toMatchObject([]);677 });678 test('Deleting message, invalid token', async () => {679 const channelId = await publicChannelId();680 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));681 await deleteTry(`/message/${channelId}/${messages[0].id}`, 403, {}, INVALID_TOKEN);682 });683 test('Deleting message, invalid channel id', async () => {684 const channelId = await publicChannelId();685 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));686 await deleteTry(`/message/999999999/${messages[0].id}`, 400, {}, await validToken(USER1));687 });688 test('Deleting message, invalid message id', async () => {689 const channelId = await publicChannelId();690 await deleteTry(`/message/${channelId}/999999999`, 400, {}, await validToken(USER1));691 });692 test('Deleting message, not channel member', async () => {693 const channelId = await publicChannelId();694 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));695 await deleteTry(`/message/${channelId}/${messages[0].id}`, 403, {}, await validToken(USER2));696 });697 test('Deleting message, not sender', async () => {698 const channelId = await publicChannelId();699 await postTry(`/channel/${channelId}/join`, 200, {}, await validToken(USER2));700 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));701 await deleteTry(`/message/${channelId}/${messages[0].id}`, 403, {}, await validToken(USER2));702 });703 test('Message hasn\'t been deleted', async () => {704 const channelId = await publicChannelId();705 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));706 expect(messages[0].image).toBe(IMAGE);707 });708 test('Deleting message', async () => {709 const channelId = await publicChannelId();710 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));711 await deleteTry(`/message/${channelId}/${messages[0].id}`, 200, {}, await validToken(USER1));712 });713 test('Message has been deleted', async () => {714 const channelId = await publicChannelId();715 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));716 expect(messages[0].image).toBe(undefined);717 expect(messages[0].message).toBe('message26');718 });719 test('Editing message, invalid token', async () => {720 const channelId = await publicChannelId();721 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));722 await putTry(`/message/${channelId}/${messages[0].id}`, 403, {723 message: 'message26!',724 }, INVALID_TOKEN);725 });726 test('Editing message, invalid channel id', async () => {727 const channelId = await publicChannelId();728 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));729 await putTry(`/message/999999999/${messages[0].id}`, 400, {730 message: 'message26!',731 }, await validToken(USER1));732 });733 test('Editing message, invalid message id', async () => {734 const channelId = await publicChannelId();735 await putTry(`/message/${channelId}/999999999`, 400, {736 message: 'message26!',737 }, await validToken(USER1));738 });739 test('Editing message, not channel member', async () => {740 const channelId = await publicChannelId();741 await postTry(`/channel/${channelId}/leave`, 200, {}, await validToken(USER2));742 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));743 await putTry(`/message/${channelId}/${messages[0].id}`, 403, {744 message: 'message26!',745 }, await validToken(USER2));746 });747 test('Editing message, no new message given', async () => {748 const channelId = await publicChannelId();749 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));750 await putTry(`/message/${channelId}/${messages[0].id}`, 400, {}, await validToken(USER1));751 });752 test('Editing message, not sender', async () => {753 const channelId = await publicChannelId();754 await postTry(`/channel/${channelId}/join`, 200, {}, await validToken(USER2));755 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));756 await putTry(`/message/${channelId}/${messages[0].id}`, 403, {757 message: 'message26!',758 }, await validToken(USER2));759 });760 test('Message hasn\'t been edited', async () => {761 const channelId = await publicChannelId();762 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));763 expect(messages[0].message).toBe('message26');764 expect(messages[0].edited).toBe(false);765 });766 test('Editing message', async () => {767 const channelId = await publicChannelId();768 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));769 await putTry(`/message/${channelId}/${messages[0].id}`, 200, {770 message: 'message26!',771 }, await validToken(USER1));772 });773 test('Viewing messages, edit reflected', async () => {774 const channelId = await publicChannelId();775 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));776 expect(messages[0].message).toBe('message26!');777 expect(messages[0].edited).toBe(true);778 expect(typeof messages[0].editedAt).toBe('string');779 });780 test('Editing message to image', async () => {781 const channelId = await publicChannelId();782 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));783 await putTry(`/message/${channelId}/${messages[0].id}`, 200, {784 image: IMAGE,785 }, await validToken(USER1));786 });787 test('Viewing messages, edit reflected #2', async () => {788 const channelId = await publicChannelId();789 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));790 expect(messages[0].message).toBe(undefined);791 expect(messages[0].image).toBe(IMAGE);792 expect(messages[0].edited).toBe(true);793 expect(typeof messages[0].editedAt).toBe('string');794 });795 test('Pinning message, invalid token', async () => {796 const channelId = await publicChannelId();797 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));798 await postTry(`/message/pin/${channelId}/${messages[1].id}`, 403, {}, INVALID_TOKEN);799 });800 test('Pinning message, invalid channel id', async () => {801 const channelId = await publicChannelId();802 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));803 await postTry(`/message/pin/999999999/${messages[1].id}`, 400, {}, await validToken(USER1));804 });805 test('Pinning message, invalid message id', async () => {806 const channelId = await publicChannelId();807 await postTry(`/message/pin/${channelId}/999999999`, 400, {}, await validToken(USER1));808 });809 test('Pinning message, not channel member', async () => {810 const channelId = await publicChannelId();811 await postTry(`/channel/${channelId}/leave`, 200, {}, await validToken(USER2));812 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));813 await postTry(`/message/pin/${channelId}/${messages[1].id}`, 403, {}, await validToken(USER2));814 });815 test('Successful pin by sender', async () => {816 const channelId = await publicChannelId();817 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));818 await postTry(`/message/pin/${channelId}/${messages[1].id}`, 200, {}, await validToken(USER1));819 });820 test('Viewing messages, pin reflected', async () => {821 const channelId = await publicChannelId();822 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));823 expect(messages[1].pinned).toBe(true);824 });825 test('Pinning already pinned message', async () => {826 const channelId = await publicChannelId();827 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));828 await postTry(`/message/pin/${channelId}/${messages[1].id}`, 400, {}, await validToken(USER1));829 });830 test('Successful pin by not-sender', async () => {831 const channelId = await publicChannelId();832 await postTry(`/channel/${channelId}/join`, 200, {}, await validToken(USER2));833 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));834 await postTry(`/message/pin/${channelId}/${messages[2].id}`, 200, {}, await validToken(USER2));835 });836 test('Viewing messages, pin reflected #2', async () => {837 const channelId = await publicChannelId();838 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));839 expect(messages[2].pinned).toBe(true);840 });841 test('Unpinning message, invalid token', async () => {842 const channelId = await publicChannelId();843 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));844 await postTry(`/message/unpin/${channelId}/${messages[1].id}`, 403, {}, INVALID_TOKEN);845 });846 test('Unpinning message, invalid channel id', async () => {847 const channelId = await publicChannelId();848 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));849 await postTry(`/message/unpin/999999999/${messages[1].id}`, 400, {}, await validToken(USER1));850 });851 test('Unpinning message, invalid message id', async () => {852 const channelId = await publicChannelId();853 await postTry(`/message/unpin/${channelId}/999999999`, 400, {}, await validToken(USER1));854 });855 test('Unpinning message, not channel member', async () => {856 const channelId = await publicChannelId();857 await postTry(`/channel/${channelId}/leave`, 200, {}, await validToken(USER2));858 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));859 await postTry(`/message/unpin/${channelId}/${messages[1].id}`, 403, {}, await validToken(USER2));860 });861 test('Successful unpin by pinner', async () => {862 const channelId = await publicChannelId();863 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));864 await postTry(`/message/unpin/${channelId}/${messages[1].id}`, 200, {}, await validToken(USER1));865 });866 test('Viewing messages, unpin reflected', async () => {867 const channelId = await publicChannelId();868 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));869 expect(messages[1].pinned).toBe(false);870 });871 test('Unpinning unpinned message', async () => {872 const channelId = await publicChannelId();873 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));874 await postTry(`/message/unpin/${channelId}/${messages[1].id}`, 400, {}, await validToken(USER1));875 });876 test('Reacting message, invalid token', async () => {877 const channelId = await publicChannelId();878 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));879 await postTry(`/message/react/${channelId}/${messages[5].id}`, 403, {880 react: 1,881 }, INVALID_TOKEN);882 });883 test('Reacting message, invalid channel id', async () => {884 const channelId = await publicChannelId();885 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));886 await postTry(`/message/react/999999999/${messages[5].id}`, 400, {887 react: 1,888 }, await validToken(USER1));889 });890 test('Reacting message, invalid message id', async () => {891 const channelId = await publicChannelId();892 await postTry(`/message/react/${channelId}/999999999`, 400, {893 react: 1,894 }, await validToken(USER1));895 });896 test('Reacting message, no react value', async () => {897 const channelId = await publicChannelId();898 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));899 await postTry(`/message/react/${channelId}/${messages[5].id}`, 400, {}, await validToken(USER1));900 });901 test('Reacting message, not channel member', async () => {902 const channelId = await publicChannelId();903 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));904 await postTry(`/message/react/${channelId}/${messages[5].id}`, 403, {905 react: 1,906 }, await validToken(USER2));907 });908 test('Reacting messages, various users/messages/types', async () => {909 const channelId = await publicChannelId();910 await postTry(`/channel/${channelId}/join`, 200, {}, await validToken(USER2));911 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));912 await postTry(`/message/react/${channelId}/${messages[5].id}`, 200, {913 react: 1,914 }, await validToken(USER1));915 await postTry(`/message/react/${channelId}/${messages[5].id}`, 200, {916 react: 2,917 }, await validToken(USER1));918 await postTry(`/message/react/${channelId}/${messages[6].id}`, 200, {919 react: 'sad',920 }, await validToken(USER1));921 await postTry(`/message/react/${channelId}/${messages[5].id}`, 200, {922 react: 2,923 }, await validToken(USER2));924 await postTry(`/message/react/${channelId}/${messages[6].id}`, 200, {925 react: 'laugh',926 }, await validToken(USER2));927 });928 test('Viewing messages, reacts reflected', async () => {929 const channelId = await publicChannelId();930 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));931 expect(messages[0].reacts).toHaveLength(0);932 expect(messages[5].reacts).toHaveLength(3);933 expect(messages[6].reacts).toHaveLength(2);934 });935 test('Can\'t react same users/messages/type twice', async () => {936 const channelId = await publicChannelId();937 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));938 await postTry(`/message/react/${channelId}/${messages[5].id}`, 400, {939 react: 1,940 }, await validToken(USER1));941 });942 test('Unreacting message, invalid token', async () => {943 const channelId = await publicChannelId();944 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));945 await postTry(`/message/unreact/${channelId}/${messages[5].id}`, 403, {946 react: 1,947 }, INVALID_TOKEN);948 });949 test('Unreacting message, invalid channel id', async () => {950 const channelId = await publicChannelId();951 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));952 await postTry(`/message/unreact/999999999/${messages[5].id}`, 400, {953 react: 1,954 }, await validToken(USER1));955 });956 test('Unreacting message, invalid message id', async () => {957 const channelId = await publicChannelId();958 await postTry(`/message/unreact/${channelId}/999999999`, 400, {959 react: 1,960 }, await validToken(USER1));961 });962 test('Unreacting message, no react value', async () => {963 const channelId = await publicChannelId();964 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));965 await postTry(`/message/unreact/${channelId}/${messages[5].id}`, 400, {}, await validToken(USER1));966 });967 test('Unreacting message, not channel member', async () => {968 const channelId = await publicChannelId();969 await postTry(`/channel/${channelId}/leave`, 200, {}, await validToken(USER2));970 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));971 await postTry(`/message/unreact/${channelId}/${messages[5].id}`, 403, {972 react: 1,973 }, await validToken(USER2));974 });975 test('Unreacting messages, various users/messages/types', async () => {976 const channelId = await publicChannelId();977 await postTry(`/channel/${channelId}/join`, 200, {}, await validToken(USER2));978 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));979 await postTry(`/message/unreact/${channelId}/${messages[5].id}`, 200, {980 react: 1,981 }, await validToken(USER1));982 await postTry(`/message/unreact/${channelId}/${messages[5].id}`, 200, {983 react: 2,984 }, await validToken(USER1));985 await postTry(`/message/unreact/${channelId}/${messages[6].id}`, 200, {986 react: 'sad',987 }, await validToken(USER1));988 await postTry(`/message/unreact/${channelId}/${messages[5].id}`, 200, {989 react: 2,990 }, await validToken(USER2));991 });992 test('Viewing messages, unreacts reflected', async () => {993 const channelId = await publicChannelId();994 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));995 expect(messages[0].reacts).toHaveLength(0);996 expect(messages[5].reacts).toHaveLength(0);997 expect(messages[6].reacts).toHaveLength(1);998 });999 test('Can\'t unreact if no react exists', async () => {1000 const channelId = await publicChannelId();1001 const { messages, } = await getTry(`/message/${channelId}?start=0`, 200, {}, await validToken(USER1));1002 await postTry(`/message/unreact/${channelId}/${messages[6].id}`, 400, {1003 react: 'laugh',1004 }, await validToken(USER1));1005 await postTry(`/message/unreact/${channelId}/${messages[6].id}`, 400, {1006 react: 1,1007 }, await validToken(USER1));1008 });...

Full Screen

Full Screen

service.js

Source:service.js Github

copy

Full Screen

1import fs from 'fs';2import jwt from 'jsonwebtoken';3import AsyncLock from 'async-lock';4import { InputError, AccessError, } from './error';5const lock = new AsyncLock();6const JWT_SECRET = 'emilywashere';7const DATABASE_FILE = './database.json';8/***************************************************************9 State Management10***************************************************************/11let users = {};12let channels = {};13let nextMessageId = 1;14const update = (users, channels, nextMessageId) =>15 new Promise((resolve, reject) => {16 lock.acquire('saveData', () => {17 try {18 fs.writeFileSync(DATABASE_FILE, JSON.stringify({19 users,20 channels,21 nextMessageId,22 }, null, 2));23 resolve();24 } catch {25 reject(new Error('Writing to database failed'));26 }27 });28 });29export const save = () => update(users, channels, nextMessageId);30export const reset = () => {31 update({}, {}, 1);32 users = {};33 channels = {};34 nextMessageId = 1;35};36try {37 const data = JSON.parse(fs.readFileSync(DATABASE_FILE));38 users = data.users;39 channels = data.channels;40 nextMessageId = data.nextMessageId;41} catch {42 console.log('WARNING: No database found, create a new one');43 save();44}45/***************************************************************46 Helper Functions47***************************************************************/48const newUserId = _ => generateId(Object.keys(users), 99999);49const newChannelId = _ => generateId(Object.keys(channels));50const getNextMessageId = _ => {51 nextMessageId += 1;52 return nextMessageId - 1;53};54const userLock = callback => new Promise((resolve, reject) => {55 lock.acquire('userAuthLock', callback(resolve, reject));56});57const channelLock = callback => new Promise((resolve, reject) => {58 lock.acquire('channelMutateLock', callback(resolve, reject));59});60const randNum = max => Math.round(Math.random() * (max - Math.floor(max / 10)) + Math.floor(max / 10));61const generateId = (currentList, max = 999999) => {62 let R = randNum(max).toString();63 while (currentList.includes(R)) {64 R = randNum(max).toString();65 }66 return R;67};68export const assertValidUserId = (userId) => userLock((resolve, reject) => {69 if (!(userId in users)) {70 return reject(new InputError('Invalid user ID'));71 }72 resolve();73});74/***************************************************************75 Auth Functions76***************************************************************/77export const getUserIdFromAuthorization = authorization => {78 try {79 const token = authorization.replace('Bearer ', '');80 const { userId, } = jwt.verify(token, JWT_SECRET);81 if (!(userId in users)) {82 throw new AccessError('Invalid token');83 }84 return userId.toString();85 } catch {86 throw new AccessError('Invalid token');87 }88};89const getUserIdFromEmail = email => {90 return Object.keys(users).find(id => users[id].email === email);91};92export const login = (email, password) => userLock((resolve, reject) => {93 const userId = getUserIdFromEmail(email);94 if (userId !== undefined && users[userId].password === password) {95 users[userId].sessionActive = true;96 resolve({97 token: jwt.sign({ userId, }, JWT_SECRET, { algorithm: 'HS256', }),98 userId: parseInt(userId, 10),99 });100 }101 reject(new InputError('Invalid email or password'));102});103export const logout = (authUserId) => userLock((resolve, reject) => {104 users[authUserId].sessionActive = false;105 resolve();106});107export const register = (email, password, name) => userLock((resolve, reject) => {108 if (getUserIdFromEmail(email) !== undefined) {109 return reject(new InputError('Email address already registered'));110 }111 const userId = newUserId();112 users[userId] = {113 email,114 name,115 password,116 bio: null,117 image: null,118 sessionActive: true,119 };120 resolve({121 token: jwt.sign({ userId, }, JWT_SECRET, { algorithm: 'HS256', }),122 userId: parseInt(userId, 10),123 });124});125/***************************************************************126 Channel Functions127***************************************************************/128// creator and members array is user ids129const newChannelPayload = (name, creator, priv, description) => ({130 name,131 creator: parseInt(creator, 10),132 private: priv,133 description,134 createdAt: new Date().toISOString(),135 members: [parseInt(creator, 10)], // eslint-disable-line136 messages: [],137});138export const assertValidChannel = (channelId) => channelLock((resolve, reject) => {139 if (!(channelId in channels)) {140 return reject(new InputError('Invalid channel ID'));141 }142 resolve();143});144const isChannelMember = (userId, channelId) => {145 return channels[channelId].members.includes(parseInt(userId, 10));146};147const assertChannelMember = (userId, channelId) => {148 if (!isChannelMember(userId, channelId)) {149 throw new AccessError('Authorised user is not a member of this channel');150 };151};152// includes private channels user is not a member of153// when marking, can use a starter db that already has private channels so tutors don't need two accounts154// Returns the basic details of each channel155export const getChannels = () => channelLock((resolve, reject) => {156 resolve(Object.keys(channels).map(key => ({157 id: parseInt(key, 10),158 name: channels[key].name,159 creator: channels[key].creator,160 private: channels[key].private,161 members: channels[key].members,162 })));163});164export const getChannel = (authUserId, channelId) => channelLock((resolve, reject) => {165 assertChannelMember(authUserId, channelId);166 const channelDetails = { ...channels[channelId], };167 delete channelDetails.messages;168 resolve(channelDetails);169});170export const addChannel = (authUserId, name, priv, description) => channelLock((resolve, reject) => {171 if (name === undefined) {172 return reject(new InputError('Must provide a name for new channel'));173 } else if (priv === undefined) {174 return reject(new InputError('Channel must have a privacy setting'));175 } else if (description === undefined) {176 return reject(new InputError('Must provide a description'));177 }178 const channelId = newChannelId();179 channels[channelId] = newChannelPayload(name, authUserId, priv, description);180 resolve(channelId);181});182export const updateChannel = (authUserId, channelId, name, description) => channelLock((resolve, reject) => {183 assertChannelMember(authUserId, channelId);184 if (name) { channels[channelId].name = name; }185 if (description) { channels[channelId].description = description; }186 resolve();187});188export const joinChannel = (authUserId, channelId) => channelLock((resolve, reject) => {189 if (isChannelMember(authUserId, channelId)) {190 return reject(new InputError('User is already a member of this channel'));191 } else if (channels[channelId].private) {192 return reject(new AccessError('You cannot join a private channel'));193 }194 channels[channelId].members.push(parseInt(authUserId, 10));195 resolve();196});197export const leaveChannel = (authUserId, channelId) => channelLock((resolve, reject) => {198 assertChannelMember(authUserId, channelId);199 const index = channels[channelId].members.indexOf(parseInt(authUserId, 10));200 channels[channelId].members.splice(index, 1);201 resolve();202});203// userId is an integer204export const inviteChannel = (authUserId, channelId, userId) => channelLock((resolve, reject) => {205 assertChannelMember(authUserId, channelId);206 if (isChannelMember(userId.toString(), channelId)) {207 return reject(new InputError('User is already a member of this channel'));208 }209 channels[channelId].members.push(userId);210 resolve();211});212/***************************************************************213 User Functions214***************************************************************/215export const getUsers = () => userLock((resolve, reject) => {216 resolve(Object.keys(users).map(key => ({217 id: parseInt(key, 10),218 email: users[key].email,219 })));220});221export const getUser = (userId) => userLock((resolve, reject) => {222 const userDetails = { ...users[userId], };223 delete userDetails.password;224 delete userDetails.sessionActive;225 resolve(userDetails);226});227export const updateProfile = (authUserId, email, password, name, bio, image) => userLock((resolve, reject) => {228 if (name) { users[authUserId].name = name; }229 if (password) { users[authUserId].password = password; }230 if (bio) { users[authUserId].bio = bio; }231 if (image) { users[authUserId].image = image; }232 if (email && getUserIdFromEmail(email) !== undefined) {233 return reject(new InputError('Email address already taken'));234 } else if (email) { users[authUserId].email = email; }235 resolve();236});237/***************************************************************238 Message Functions239***************************************************************/240const findMsgIdxInChannel = (chId, mId) => {241 const index = channels[chId].messages.findIndex(m => m.id === parseInt(mId, 10));242 if (index === -1) {243 throw new InputError('No message with this message ID exists in this channel');244 }245 return index;246};247const isInvalidMessage = (m) => {248 return typeof m !== 'string' && m !== undefined;249};250// start is an int251export const getMessages = (authUserId, channelId, start) => channelLock((resolve, reject) => {252 if (Number.isNaN(start)) {253 return reject(new InputError('Invalid start value'));254 } else if (start < 0) {255 return reject(new InputError('Start value cannot be negative'));256 }257 assertChannelMember(authUserId, channelId);258 resolve(channels[channelId].messages.slice(start, start + 25));259});260export const sendMessage = (authUserId, channelId, message, image) => channelLock((resolve, reject) => {261 if ((isInvalidMessage(message) || isInvalidMessage(image)) || (message === undefined && image === undefined)) {262 return reject(new InputError('Invalid message or image'));263 }264 assertChannelMember(authUserId, channelId);265 channels[channelId].messages.unshift({266 id: getNextMessageId(),267 message,268 image,269 sender: parseInt(authUserId, 10),270 sentAt: new Date().toISOString(),271 edited: false,272 editedAt: null,273 pinned: false,274 reacts: [],275 });276 resolve();277});278export const deleteMessage = (authUserId, channelId, messageId) => channelLock((resolve, reject) => {279 assertChannelMember(authUserId, channelId);280 const messageIndex = findMsgIdxInChannel(channelId, messageId);281 if (channels[channelId].messages[messageIndex].sender !== parseInt(authUserId, 10)) {282 return reject(new AccessError('You can\'t delete a message you didn\'t send'));283 }284 channels[channelId].messages.splice(messageIndex, 1);285 resolve();286});287export const editMessage = (authUserId, channelId, messageId, newMessage, newImage) => channelLock((resolve, reject) => {288 if ((isInvalidMessage(newMessage) || isInvalidMessage(newImage)) || (newMessage === undefined && newImage === undefined)) {289 return reject(new InputError('Invalid message or image'));290 }291 assertChannelMember(authUserId, channelId);292 const messageIndex = findMsgIdxInChannel(channelId, messageId);293 if (channels[channelId].messages[messageIndex].sender !== parseInt(authUserId, 10)) {294 return reject(new AccessError('You can\'t edit a message you didn\'t send'));295 }296 channels[channelId].messages[messageIndex].message = newMessage;297 channels[channelId].messages[messageIndex].image = newImage;298 channels[channelId].messages[messageIndex].edited = true;299 channels[channelId].messages[messageIndex].editedAt = new Date().toISOString();300 resolve();301});302export const pinMessage = (authUserId, channelId, messageId) => channelLock((resolve, reject) => {303 assertChannelMember(authUserId, channelId);304 const messageIndex = findMsgIdxInChannel(channelId, messageId);305 if (channels[channelId].messages[messageIndex].pinned) {306 return reject(new InputError('This message is already pinned'));307 }308 channels[channelId].messages[messageIndex].pinned = true;309 resolve();310});311export const unpinMessage = (authUserId, channelId, messageId) => channelLock((resolve, reject) => {312 assertChannelMember(authUserId, channelId);313 const messageIndex = findMsgIdxInChannel(channelId, messageId);314 if (!channels[channelId].messages[messageIndex].pinned) {315 return reject(new InputError('This message is not pinned'));316 }317 channels[channelId].messages[messageIndex].pinned = false;318 resolve();319});320export const reactMessage = (authUserId, channelId, messageId, react) => channelLock((resolve, reject) => {321 if (react === undefined) {322 return reject(new InputError('No react value provided'));323 }324 assertChannelMember(authUserId, channelId);325 const messageIndex = findMsgIdxInChannel(channelId, messageId);326 if (channels[channelId].messages[messageIndex].reacts.findIndex(327 r => r.user === parseInt(authUserId, 10) && r.react === react328 ) !== -1) {329 return reject(new InputError('This message already contains a react of this type from this user'));330 }331 channels[channelId].messages[messageIndex].reacts.push({332 user: parseInt(authUserId, 10),333 react,334 });335 resolve();336});337export const unreactMessage = (authUserId, channelId, messageId, react) => channelLock((resolve, reject) => {338 if (react === undefined) {339 return reject(new InputError('No react value provided'));340 }341 assertChannelMember(authUserId, channelId);342 const messageIndex = findMsgIdxInChannel(channelId, messageId);343 const reactIndex = channels[channelId].messages[messageIndex].reacts.findIndex(344 r => r.user === parseInt(authUserId, 10) && r.react === react345 );346 if (reactIndex === -1) {347 return reject(new InputError('This message does not contain a react of this type from this user'));348 }349 channels[channelId].messages[messageIndex].reacts.splice(reactIndex, 1);350 resolve();...

Full Screen

Full Screen

native.js

Source:native.js Github

copy

Full Screen

1const mlink = require('../index')2const Router = mlink.Router3const DeviceManager = require('../managers/device_manager')4const config = require('../../config')5const {6 bundleWrapper,7 transformUrlToLocalUrl,8 generateSandboxWorkerEntry,9 generateWorkerEntry10} = require('../../util/wrapper')11const MemoryFile = require('../../MemoryFile')12const debuggerRouter = Router.get('debugger')13const crypto = require('../../util/crypto')14const path = require('path')15config.env = {}16config.wmlEnv = {}17let heartbeatTimer18const sendHeartbeat = () => {19 heartbeatTimer && clearTimeout(heartbeatTimer)20 heartbeatTimer = setTimeout(() => {21 debuggerRouter.pushMessage('proxy.native', 'ping')22 sendHeartbeat()23 }, config.heartbeatTime)24}25debuggerRouter26 .registerHandler(function (message) {27 sendHeartbeat()28 const payload = message.payload29 const method = payload.method30 const device = DeviceManager.getDevice(message.channelId)31 if (method === 'WxDebug.initJSRuntime') {32 if (!config.env[message.channelId]) {33 config.env[message.channelId] = {}34 }35 config.env[message.channelId]['jsframework'] = new MemoryFile(36 'js-framework.js',37 payload.params.source38 ).getUrl()39 if (device && device.logLevel) {40 payload.params.env.WXEnvironment.logLevel = device.logLevel41 }42 config.env[message.channelId]['isLayoutAndSandbox'] =43 payload.params.isLayoutAndSandbox44 config.env[message.channelId]['environment'] = payload.params.env45 config.env[message.channelId]['device'] = device46 }47 else if (48 method === 'WxDebug.callJS' &&49 payload.params.method === 'createInstance'50 ) {51 const code = payload.params.args[1]52 let bundleUrl =53 payload.params.args[2].bundleUrl || crypto.md5(code) + '.js'54 let env = {55 environment: config.env[message.channelId]['environment'],56 device: config.env[message.channelId]['device'],57 isLayoutAndSandbox: config.env[message.channelId]['isLayoutAndSandbox']58 }59 if (60 /^(https?|taobao|qap):\/\/(.*your_current_ip):(\d+)\//i.test(bundleUrl)61 ) {62 bundleUrl = bundleUrl.replace(63 /^(https?|taobao|qap):\/\/(.*your_current_ip):(\d+)\//i,64 'file://'65 )66 }67 env['sourceUrl'] = new MemoryFile(68 bundleUrl,69 bundleWrapper(code, transformUrlToLocalUrl(bundleUrl))70 ).getUrl()71 if (72 config.env[message.channelId] &&73 config.env[message.channelId]['polify'] &&74 config.env[message.channelId]['polify']['jsframework']75 ) {76 env['jsframework'] =77 config.env[message.channelId]['polify']['jsframework']78 }79 else {80 env['jsframework'] = config.env[message.channelId]['jsframework']81 }82 config.env[message.channelId]['workerjs'] = payload.params.workerjs = new MemoryFile(83 `[Runtime]/${path.basename(bundleUrl)}`,84 generateWorkerEntry(env)85 ).getUrl()86 if (87 config.env[message.channelId]['polify'] &&88 config.env[message.channelId]['polify']['workerjs']89 ) {90 env['workerjs'] = config.env[message.channelId]['polify']['workerjs']91 }92 else {93 env['workerjs'] = config.env[message.channelId]['workerjs']94 }95 payload.params.workerjs = env['workerjs']96 if (97 config.env[message.channelId]['polify'] &&98 Array.isArray(config.env[message.channelId]['polify']['jsservice']) &&99 config.env[message.channelId]['polify']['jsservice'].length > 0100 ) {101 payload.params.jsservice =102 config.env[message.channelId]['polify']['jsservice']103 }104 else {105 payload.params.jsservice = config.env[message.channelId]['jsservice']106 }107 if (108 config.env[message.channelId] &&109 config.env[message.channelId]['polify'] &&110 config.env[message.channelId]['polify']['sourcejs']111 ) {112 bundleUrl = payload.params.sourceUrl = config.env[message.channelId]['polify']['sourcejs']113 }114 else {115 bundleUrl = payload.params.sourceUrl = env['sourceUrl']116 }117 debuggerRouter.pushMessageByChannelId(118 'page.debugger',119 message.channelId,120 {121 method: 'WxDebug.bundleRendered',122 params: {123 bundleUrl: bundleUrl,124 env: {125 jsframework: config.env[message.channelId]['jsframework'],126 jsservice: payload.params.jsservice,127 workerjs: payload.params.workerjs,128 sourcejs: payload.params.sourceUrl129 },130 isSandbox: false131 }132 }133 )134 }135 else if (136 method === 'WxDebug.callJS' &&137 payload.params.method === 'destroyInstance'138 ) {139 config.ACTIVE_INSTANCEID = ''140 }141 else if (142 method === 'WxDebug.callJS' &&143 payload.params.method === 'createInstanceContext'144 ) {145 const options = payload.params.args[1]146 const dependenceCode = payload.params.args[3]147 let env = {148 environment: config.env[message.channelId]['environment'],149 device: config.env[message.channelId]['device'],150 isLayoutAndSandbox: config.env[message.channelId]['isLayoutAndSandbox']151 }152 let bundleUrl = options.bundleUrl153 if (154 /^(https?|taobao|qap):\/\/(.*your_current_ip):(\d+)\//i.test(bundleUrl)155 ) {156 bundleUrl =157 '/source/' +158 bundleUrl.replace(159 /^(https?|taobao|qap):\/\/(.*your_current_ip):(\d+)\//i,160 'file://'161 )162 }163 else if (/^file:\/\//.test(bundleUrl)) {164 bundleUrl = '/source/' + bundleUrl165 }166 else {167 bundleUrl = '/source/' + bundleUrl168 }169 config.ACTIVE_INSTANCEID = payload.params.args[0]170 if (dependenceCode) {171 config.env[message.channelId]['dependencejs'] = new MemoryFile(172 `dependencejs.js`,173 dependenceCode174 ).getUrl()175 if (176 config.env[message.channelId]['polify'] &&177 config.env[message.channelId]['polify']['dependencejs']178 ) {179 payload.params.dependencejs =180 config.env[message.channelId]['polify']['dependencejs']181 }182 else {183 payload.params.dependencejs =184 config.env[message.channelId]['dependencejs']185 }186 }187 if (188 config.env[message.channelId] &&189 config.env[message.channelId]['polify'] &&190 config.env[message.channelId]['polify']['jsservice']191 ) {192 payload.params.jsservice =193 config.env[message.channelId]['polify']['jsservice']194 }195 else {196 payload.params.jsservice = config.env[message.channelId]['jsservice']197 }198 if (199 config.env[message.channelId] &&200 config.env[message.channelId]['polify'] &&201 config.env[message.channelId]['polify']['jsframework']202 ) {203 env['jsframework'] =204 config.env[message.channelId]['polify']['jsframework']205 }206 else {207 env['jsframework'] = config.env[message.channelId]['jsframework']208 }209 env['isLayoutAndSandbox'] =210 config.env[message.channelId]['isLayoutAndSandbox']211 config.env[message.channelId]['workerjs'] = payload.params.workerjs = new MemoryFile(212 `[Runtime]/${path.basename(bundleUrl || '')}`,213 generateSandboxWorkerEntry(env)214 ).getUrl()215 if (216 config.env[message.channelId] &&217 config.env[message.channelId]['polify'] &&218 config.env[message.channelId]['polify']['workerjs']219 ) {220 payload.params.workerjs =221 config.env[message.channelId]['polify']['workerjs']222 }223 else {224 payload.params.workerjs = config.env[message.channelId]['workerjs']225 }226 if (227 config.env[message.channelId] &&228 config.env[message.channelId]['polify'] &&229 config.env[message.channelId]['polify']['sourcejs']230 ) {231 bundleUrl = config.env[message.channelId]['polify']['sourcejs']232 }233 else if (config.env[message.channelId]['sourcejs']) {234 bundleUrl = config.env[message.channelId]['sourcejs']235 }236 debuggerRouter.pushMessageByChannelId(237 'page.debugger',238 message.channelId,239 {240 method: 'WxDebug.bundleRendered',241 params: {242 bundleUrl: bundleUrl,243 env: {244 jsframework: env['jsframework'],245 jsservice: payload.params.jsservice,246 workerjs: payload.params.workerjs,247 dependencejs: payload.params.dependencejs,248 sourcejs: bundleUrl249 },250 isSandbox: true251 }252 }253 )254 }255 else if (256 method === 'WxDebug.callJS' &&257 payload.params.method === 'importScript'258 ) {259 const code = payload.params.args[1]260 let bundleUrl =261 (payload.params.args[2] && payload.params.args[2].bundleUrl) ||262 crypto.md5(code) + '.js'263 bundleUrl = bundleUrl.replace(/\?random=(-)?\d+/i, '')264 if (!config.env[message.channelId]) {265 config.env[message.channelId] = {}266 }267 if (268 config.env[message.channelId] &&269 config.env[message.channelId]['polify'] &&270 config.env[message.channelId]['polify']['sourcejs']271 ) {272 payload.params.sourceUrl =273 config.env[message.channelId]['polify']['sourcejs']274 }275 else {276 config.env[message.channelId]['sourcejs'] = payload.params.sourceUrl = new MemoryFile(bundleUrl, code).getUrl()277 }278 }279 else if (method === 'WxDebug.importScript') {280 const code = payload.params.source281 const url = new MemoryFile(282 `jsservice_${crypto.md5(code)}.js`,283 payload.params.source284 ).getUrl()285 if (!config.env[message.channelId]['jsservice']) {286 config.env[message.channelId]['jsservice'] = []287 }288 if (config.env[message.channelId]['jsservice'].indexOf(url) === -1) {289 config.env[message.channelId]['jsservice'].push(url)290 }291 }292 else if (method === 'syncReturn') {293 message.payload = {294 error: payload.error,295 ret: payload.params && payload.params.ret296 }297 message.to('sync.native')298 return299 }300 else if (method === 'WxDebug.sendTracingData') {301 message.to('page.debugger')302 return303 }304 else if (method === 'WxDebug.sendSummaryInfo') {305 message.to('page.debugger')306 return307 }308 else if (method === 'WxDebug.sendPerformanceData') {309 message.to('page.debugger')310 return311 }312 message.to('runtime.worker')313 })314 .at('proxy.native')315 .when('payload.method&&payload.method.split(".")[0]==="WxDebug"')316debuggerRouter317 .registerHandler(function (message) {318 sendHeartbeat()319 const payload = message.payload320 const device = DeviceManager.getDevice(message.channelId)321 if (payload.method === 'Page.screencastFrame') {322 payload.params.sessionId = 1323 if (device && device.platform === 'android') {324 payload.params.metadata.pageScaleFactor = 0.999325 }326 }327 else if (payload.method === 'Console.messageAdded') {328 // issue: https://github.com/weexteam/weex-toolkit/issues/408329 // TODO: make it can be control by user330 if (device && device.remoteDebug) {331 message.discard()332 }333 else {334 message.payload = {335 method: 'Runtime.consoleAPICalled',336 params: {337 type: payload.params.message.level,338 args:339 [340 {341 type: 'string',342 value: payload.params.message.text343 }344 ] || [],345 executionContextId: 1346 // "stackTrace": payload.params.message.stackTrace347 }348 }349 }350 }351 else if (352 payload.result &&353 payload.result.method === 'WxDebug.syncReturn'354 ) {355 message.payload = {356 id:357 payload.result.params &&358 payload.result.id &&359 payload.result.params.syncId,360 error: payload.error,361 ret: payload.result.params && payload.result.params.ret362 }363 message.to('sync.native')364 return365 }366 else if (payload.result && payload.id === undefined) {367 message.discard()368 }369 message.to('proxy.inspector')370 })371 .at('proxy.native')372 .when(373 '!payload.method||(payload.method.split(".")[0]!=="WxDebug")'...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1const { bot, log, web3 } = require('./common');23// Initialize Discord Bot45bot.on('ready', function (evt) {6 log.info('[Bridgett-bot/index.js] Connected');7 log.info('[Bridgett-bot/index.js] Logged in as: ');8 log.info('[Bridgett-bot/index.js]' + bot.username + ' - (' + bot.id + ')');9});1011function isNumber(n) {12 return !isNaN(parseFloat(n)) && isFinite(n);13}1415//* Get functions from library *//1617const { getBlockNumber, getBalance, getTransaction, sendSignedTransaction, getGasPrice, getBlock, version, error } = require( "./funcs" );1819// dapps2021const { statebot, multi, donate, getetc, etcmail, eventLog, tipper, atlantis } = require( "./dapps" );2223// help files2425const { bridgette, donatehelp, etcmailhelp, tipperError } = require( "./help" );2627//* end functoin set*//2829function addReaction(channelID, evt,emoji){30 bot.addReaction({31 channelID : channelID,32 messageID : evt.d.id,33 reaction : emoji34 })35}3637bot.on('message', async function (user, userID, channelID, message, evt) {38 // Our bot needs to know if it will execute a command39 // It will listen for messages that will start with `!`4041 if (message.substring(0, 1) == '!') {42 var args = message.substring(1).split(' ');43 var cmd = args[0].toLowerCase();44 var payload = args[1];45 if (args[2] != null){46 var dLoad = [args[1].toLowerCase(), args[2], args[3]];47 }48 args = args.splice(1);49 switch(cmd) {50 case 'web3':51 bot.sendMessage(bridgette(channelID));52 break;5354 // getBlockNumber55 case 'getblocknumber':56 web3.eth.getBlockNumber()57 .then(blockNumber => {58 bot.sendMessage(getBlockNumber(channelID, blockNumber));59 }).catch((err) => {60 bot.sendMessage(error(channelID, err))61 });62 break;6364 // version65 case 'version':66 bot.sendMessage(version(channelID));67 break;6869 // getBalance70 case 'getbalance':71 if(payload != undefined && web3.utils.isAddress(payload)){72 web3.eth.getBalance(payload)73 .then( balance => {74 bot.sendMessage(getBalance(channelID, payload, balance));75 }).catch((err) => {76 bot.sendMessage(error(channelID, err))77 });78 } else {79 bot.sendMessage({80 to: channelID,81 message: "Get balance requires an account number (i.e. !getBalance <0xaccount>)"82 });83 }84 break;8586 // getTransaction87 case 'gettransaction':88 if(payload != undefined){89 web3.eth.getTransaction(payload).then(90 transaction => {91 bot.sendMessage(getTransaction(channelID, payload, transaction));92 }).catch((err) => {93 bot.sendMessage(error(channelID, err))94 });95 } else {96 bot.sendMessage({97 to: channelID,98 message: "Get transaction requires a txId (i.e. !getTransaction <txId>)"99 });100 }101 break;102103 // sendSignedTransaction104 case 'sendsignedtransaction':105 if(payload != undefined){106 web3.eth.sendSignedTransaction(payload)107 .then( hash => {108 bot.sendMessage(sendSignedTransaction(channelID, hash))109 }).catch((err) => {110 bot.sendMessage(error(channelID, err))111 });112 } else {113 bot.sendMessage({114 to: channelID,115 message: "Send Raw Tx requires a signed transaction (i.e. !sendRawTransaction <0xdeadbeef>)"116 });117 }118 break;119120 // gasPrice121 case 'gasprice' :122 web3.eth.getGasPrice()123 .then(gas => {124 bot.sendMessage(getGasPrice(channelID, gas))125 }).catch((err) => {126 bot.sendMessage(error(channelID, err))127 });128 break;129130 // getBlock131 case 'getblock':132 addReaction(channelID, evt, "\u{1F916}");133 if(payload != undefined){134 var funcs = args[2];135 web3.eth.getBlock(payload)136 .then( rawBlk => {137 bot.sendMessage(getBlock(channelID, funcs, rawBlk))138 }).catch((err) => {139 bot.sendMessage(error(channelID, err))140 });141 } else {142 bot.sendMessage({143 to: channelID,144 message: "Get transaction requires a txId (i.e. !getTransaction <txId>)"145 });146 }147148 break;149150 case 'query':151 if(payload != undefined && isNumber(payload)){152 if(web3.utils.isAddress(payload)){153 web3.eth.getBalance(payload)154 .then( balance => {155 bot.sendMessage(getBalance(channelID, payload, balance));156 }).catch((err) => {157 bot.sendMessage(error(channelID, err))158 });159 } else if (payload.length == 66 ){160 web3.eth.getTransaction(payload).then(161 transaction => {162 bot.sendMessage(getTransaction(channelID, payload, transaction));163 })164 } else if (payload.length <= 9) {165 web3.eth.getBlock(payload)166 .then( rawBlk => {167 bot.sendMessage(getBlock(channelID, funcs, rawBlk))168 })169 .catch((err) => {170 bot.sendMessage(error(channelID, err))171 });172 } else {173 bot.sendMessage({174 to: channelID,175 message: "Query requires a payload of txId, or account, block number, or something (i.e. !query <something>)"176 });177 }178 } else {179 bot.sendMessage({180 to: channelID,181 message: "Query requires a payload of txId, or account, block number, or something (i.e. !query <something>)"182 });183 };184 break;185186//* dapps *//187 case 'atlantis':188 web3.eth.getBlockNumber()189 .then(blockNumber => {190 bot.sendMessage(atlantis(channelID, blockNumber));191 }).catch((err) => {192 bot.sendMessage(error(channelID, err))193 });194 break;195196 case 'statebot':197 statebot.methods.currentAddr().call()198 .then( ca => {199 bot.sendMessage({200 to: channelID,201 message : "The most current state dump is located at http://ipfs.io/ipfs/" +ca202 });203 });204 break;205206 case 'community':207 if(payload != undefined){208 switch(payload) {209 case 'address':210 bot.sendMessage({211 to: channelID,212 message : "The community multisig is located at: `" + multi.options.address + "`"213 });214 break;215 case 'balance':216 web3.eth.getBalance(multi.options.address)217 .then (res => {218 bot.sendMessage(getBalance(channelID, "Community Multisig", res))219 });220 break;221 }222 } else {223 bot.sendMessage({224 to: channelID,225 message : "Please use either `!community balance` or `!community address`"226 });227 }228 break;229 case 'donate' :230 if(payload != undefined){231 bot.sendMessage({232 to: channelID,233 message : 'Creating a contract with ' + dLoad[2] +' as the owner giving ' + dLoad[1] +'% of anything donated to '+ dLoad[0] + '.'234 });235 bot.sendMessage(await donate(channelID, user,dLoad))236 } else {237 bot.sendMessage(donatehelp(channelID));238 }239 break;240241 case 'getetc' :242 if(payload != undefined && web3.utils.isAddress(payload)){243 bot.sendMessage({244 to: channelID,245 message : 'Ok, I\'ll see if I can send some gas money.'246 });247 bot.sendMessage(await getetc(channelID, user, payload))248 } else {249 bot.sendMessage({250 to: channelID,251 message : "Sorry" + user + " try again with an address!"252 });253 }254 break;255256 case 'mail' :257 if(payload != undefined){258 addReaction(channelID, evt, "\u{1F916}");259 bot.sendMessage(await etcmail(channelID, user, args)260 .catch((err) => {261 addReaction(channelID, evt, "⛔");262 console.error(err)}));263 } else {264 bot.sendMessage(etcmailhelp(channelID));265 }266 break;267268 case 'tipper' :269 if(payload != undefined){270 await tipper(channelID, user, userID, args, evt)271 } else {272 addReaction(channelID, evt, "⚠️");273 bot.sendMessage(tipperError(channelID));274 }275 break;276277 case 'events' :278 bot.sendMessage(await eventLog(channelID, user, payload));279 break;280281 }282 }283});284 ...

Full Screen

Full Screen

server.js

Source:server.js Github

copy

Full Screen

1import fs from 'fs';2import express from 'express';3import swaggerUi from 'swagger-ui-express';4import cors from 'cors';5import { InputError, AccessError, } from './error';6import { BACKEND_PORT } from '../../frontend/src/config';7import swaggerDocument from '../swagger.json';8import {9 save,10 getUserIdFromAuthorization,11 login,12 logout,13 register,14 assertValidChannel,15 assertValidUserId,16 getChannels,17 getChannel,18 addChannel,19 updateChannel,20 joinChannel,21 leaveChannel,22 inviteChannel,23 getUsers,24 getUser,25 updateProfile,26 getMessages,27 sendMessage,28 deleteMessage,29 editMessage,30 pinMessage,31 unpinMessage,32 reactMessage,33 unreactMessage,34} from './service';35const app = express();36app.use(cors());37app.use(express.urlencoded({ extended: true, }));38app.use(express.json({ limit: '50mb', }));39const catchErrors = fn => async (req, res) => {40 try {41 await fn(req, res);42 save();43 } catch (err) {44 if (err instanceof InputError) {45 res.status(400).send({ error: err.message, });46 } else if (err instanceof AccessError) {47 res.status(403).send({ error: err.message, });48 } else {49 console.log(err);50 res.status(500).send({ error: 'A system error ocurred', });51 }52 }53};54/***************************************************************55 Auth Functions56***************************************************************/57const authed = fn => async (req, res) => {58 const userId = getUserIdFromAuthorization(req.header('Authorization'));59 await fn(req, res, userId);60};61app.post('/auth/login', catchErrors(async (req, res) => {62 const { email, password, } = req.body;63 return res.json(await login(email, password));64}));65app.post('/auth/register', catchErrors(async (req, res) => {66 const { email, password, name, } = req.body;67 return res.json(await register(email, password, name));68}));69app.post('/auth/logout', catchErrors(authed(async (req, res, authUserId) => {70 await logout(authUserId);71 return res.json({});72})));73/***************************************************************74 Channel Functions75***************************************************************/76app.get('/channel', catchErrors(authed(async (req, res, authUserId) => {77 return res.json({ channels: await getChannels(), });78})));79app.get('/channel/:channelId', catchErrors(authed(async (req, res, authUserId) => {80 const { channelId, } = req.params;81 await assertValidChannel(channelId);82 return res.json(await getChannel(authUserId, channelId));83})));84app.post('/channel', catchErrors(authed(async (req, res, authUserId) => {85 const { name, _, description, } = req.body;86 return res.json({87 channelId: await addChannel(authUserId, name, req.body.private, description),88 });89})));90app.put('/channel/:channelId', catchErrors(authed(async (req, res, authUserId) => {91 const { channelId, } = req.params;92 const { name, description, } = req.body;93 await assertValidChannel(channelId);94 await updateChannel(authUserId, channelId, name, description);95 return res.status(200).send({});96})));97app.post('/channel/:channelId/join', catchErrors(authed(async (req, res, authUserId) => {98 const { channelId, } = req.params;99 await assertValidChannel(channelId);100 await joinChannel(authUserId, channelId);101 return res.status(200).send({});102})));103app.post('/channel/:channelId/leave', catchErrors(authed(async (req, res, authUserId) => {104 const { channelId, } = req.params;105 await assertValidChannel(channelId);106 await leaveChannel(authUserId, channelId);107 return res.status(200).send({});108})));109app.post('/channel/:channelId/invite', catchErrors(authed(async (req, res, authUserId) => {110 const { channelId, } = req.params;111 const { userId, } = req.body;112 await assertValidChannel(channelId);113 await assertValidUserId(userId.toString());114 await inviteChannel(authUserId, channelId, userId);115 return res.status(200).send({});116})));117/***************************************************************118 User Functions119***************************************************************/120app.get('/user', catchErrors(authed(async (req, res, authUserId) => {121 return res.json({ users: await getUsers(), });122})));123app.get('/user/:userId', catchErrors(authed(async (req, res, authUserId) => {124 const { userId, } = req.params;125 await assertValidUserId(userId);126 return res.json(await getUser(userId));127})));128app.put('/user', catchErrors(authed(async (req, res, authUserId) => {129 const { email, password, name, bio, image, } = req.body;130 await updateProfile(authUserId, email, password, name, bio, image);131 return res.status(200).send({});132})));133/***************************************************************134 Message Functions135***************************************************************/136app.get('/message/:channelId', catchErrors(authed(async (req, res, authUserId) => {137 const { channelId, } = req.params;138 const { start, } = req.query;139 await assertValidChannel(channelId);140 return res.json({ messages: await getMessages(authUserId, channelId, parseInt(start, 10)), });141})));142app.post('/message/:channelId', catchErrors(authed(async (req, res, authUserId) => {143 const { channelId, } = req.params;144 const { message, image, } = req.body;145 await assertValidChannel(channelId);146 await sendMessage(authUserId, channelId, message, image);147 return res.status(200).send({});148})));149app.put('/message/:channelId/:messageId', catchErrors(authed(async (req, res, authUserId) => {150 const { channelId, messageId, } = req.params;151 const { message, image, } = req.body;152 await assertValidChannel(channelId);153 await editMessage(authUserId, channelId, messageId, message, image);154 return res.status(200).send({});155})));156app.delete('/message/:channelId/:messageId', catchErrors(authed(async (req, res, authUserId) => {157 const { channelId, messageId, } = req.params;158 await assertValidChannel(channelId);159 await deleteMessage(authUserId, channelId, messageId);160 return res.status(200).send({});161})));162app.post('/message/pin/:channelId/:messageId', catchErrors(authed(async (req, res, authUserId) => {163 const { channelId, messageId, } = req.params;164 await assertValidChannel(channelId);165 await pinMessage(authUserId, channelId, messageId);166 return res.status(200).send({});167})));168app.post('/message/unpin/:channelId/:messageId', catchErrors(authed(async (req, res, authUserId) => {169 const { channelId, messageId, } = req.params;170 await assertValidChannel(channelId);171 await unpinMessage(authUserId, channelId, messageId);172 return res.status(200).send({});173})));174app.post('/message/react/:channelId/:messageId', catchErrors(authed(async (req, res, authUserId) => {175 const { channelId, messageId, } = req.params;176 const { react, } = req.body;177 await assertValidChannel(channelId);178 await reactMessage(authUserId, channelId, messageId, react);179 return res.status(200).send({});180})));181app.post('/message/unreact/:channelId/:messageId', catchErrors(authed(async (req, res, authUserId) => {182 const { channelId, messageId, } = req.params;183 const { react, } = req.body;184 await assertValidChannel(channelId);185 await unreactMessage(authUserId, channelId, messageId, react);186 return res.status(200).send({});187})));188/***************************************************************189 Running Server190***************************************************************/191app.get('/', (req, res) => res.redirect('/docs'));192app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));193const port = BACKEND_PORT || 5000;194const server = app.listen(port, () => {195 console.log(`Backend is now listening on port ${port}!`);196 console.log(`For API docs, navigate to http://localhost:${port}`);197});...

Full Screen

Full Screen

database.test.js

Source:database.test.js Github

copy

Full Screen

1import request from 'supertest';2import server from '../src/server';3import { reset } from '../src/service';4const postTry = async (path, payload, token) => sendTry('post', path, payload, token);5const getTry = async (path, payload, token) => sendTry('get', path, payload, token);6const sendTry = async (typeFn, path, payload = {}, token = null) => {7 let req = request(server);8 if (typeFn === 'post') {9 req = req.post(path);10 } else if (typeFn === 'get') {11 req = req.get(path);12 } else if (typeFn === 'delete') {13 req = req.delete(path);14 } else if (typeFn === 'put') {15 req = req.put(path);16 }17 if (token !== null) {18 req = req.set('Authorization', `Bearer ${token}`);19 }20 const response = await req.send(payload);21 return response.body;22};23describe('Making the database', () => {24 beforeAll(() => {25 reset();26 });27 beforeAll(() => {28 server.close();29 });30 test('Public channel', async () => {31 let body = await postTry('/auth/register', {32 email: 'mia@email.com',33 password: 'solongbouldercity',34 name: 'Mia',35 });36 const mia = body.token;37 body = await postTry('/auth/register', {38 email: 'sebastian@email.com',39 password: 'chickenonastick',40 name: 'Sebastian',41 });42 const seb = body.token;43 body = await postTry('/channel', {44 name: 'public channel',45 private: false,46 description: '',47 }, mia);48 const channelId = body.channelId;49 const { users, } = await getTry('/user', {}, mia);50 const sebId = users.find(u => u.email === 'sebastian@email.com').id;51 await postTry(`/channel/${channelId}/invite`, {52 userId: sebId,53 }, mia);54 await postTry(`/message/${channelId}`, {55 message: 'when do you leave? in the morning?',56 }, mia);57 await postTry(`/message/${channelId}`, {58 message: 'yeah, 6:45. boise',59 }, seb);60 await postTry(`/message/${channelId}`, {61 message: 'boise?',62 }, mia);63 await postTry(`/message/${channelId}`, {64 message: 'boise',65 }, seb);66 await postTry(`/message/${channelId}`, {67 message: 'to boise!',68 }, mia);69 await postTry(`/message/${channelId}`, {70 message: 'you should come',71 }, seb);72 await postTry(`/message/${channelId}`, {73 message: 'to boise?',74 }, mia);75 await postTry(`/message/${channelId}`, {76 message: 'yeah, you can knock that off your bucketlist',77 }, seb);78 await postTry(`/message/${channelId}`, {79 message: 'oh, that would be... really exciting. i wish i could',80 }, mia);81 await postTry(`/message/${channelId}`, {82 message: 'what are you doing after the tour?',83 }, mia);84 await postTry(`/message/${channelId}`, {85 message: 'why can\'t you?',86 }, seb);87 await postTry(`/message/${channelId}`, {88 message: 'come to boise?',89 }, mia);90 await postTry(`/message/${channelId}`, {91 message: 'yeah',92 }, seb);93 await postTry(`/message/${channelId}`, {94 message: 'cause i have to rehearse',95 }, mia);96 await postTry(`/message/${channelId}`, {97 message: 'yeah, but can\'t you rehearse anywhere?',98 }, seb);99 await postTry(`/message/${channelId}`, {100 message: '...anywhere you are?',101 }, mia);102 await postTry(`/message/${channelId}`, {103 message: 'i mean... i guess',104 }, seb);105 await postTry(`/message/${channelId}`, {106 message: 'um... well all my stuff is here and it\'s in two weeks',107 }, mia);108 await postTry(`/message/${channelId}`, {109 message: 'so i don\'t really think that would be...',110 }, mia);111 await postTry(`/message/${channelId}`, {112 message: 'okay',113 }, seb);114 await postTry(`/message/${channelId}`, {115 message: 'the best idea right now',116 }, mia);117 await postTry(`/message/${channelId}`, {118 message: 'well...',119 }, seb);120 await postTry(`/message/${channelId}`, {121 message: 'but... i wish i could',122 }, mia);123 await postTry(`/message/${channelId}`, {124 message: 'we\'re just gonna have to try and see each other, y\'know, so that we see each other',125 }, seb);126 await postTry(`/message/${channelId}`, {127 message: 'i know, but when are you done?',128 }, mia);129 await postTry(`/message/${channelId}`, {130 message: 'what do you mean? i mean...',131 }, seb);132 await postTry(`/message/${channelId}`, {133 message: 'when are you finished with the whole tour?',134 }, mia);135 await postTry(`/message/${channelId}`, {136 message: 'but after we finish, we\'re gonna go to record and then we\'ll go back on tour',137 }, seb);138 await postTry(`/message/${channelId}`, {139 message: 'you know, we tour so we can make the record so we can go back and tour the record',140 }, seb);141 await postTry(`/message/${channelId}`, {142 message: 'so it\'s like the long haul?',143 }, mia);144 await postTry(`/message/${channelId}`, {145 message: 'what do you mean "the long haul"?',146 }, seb);147 await postTry(`/message/${channelId}`, {148 message: 'i mean the long haul, like you\'re gonna stay in this band... for a long time... on tour',149 }, mia);150 await postTry(`/message/${channelId}`, {151 message: 'i mean, what did you think i was gonna do?',152 }, seb);153 await postTry(`/message/${channelId}`, {154 message: 'i don\'t... i hadn\'t really thought it through. i didn\'t know that the band... was so important',155 }, mia);156 await postTry(`/message/${channelId}`, {157 message: 'you didn\'t think it would be successful',158 }, seb);159 await postTry(`/message/${channelId}`, {160 message: 'um... no, that\'s not really what i mean. i just mean that you, i mean, you\'re gonna be on tour for what? months now? years?',161 }, mia);162 await postTry(`/message/${channelId}`, {163 message: 'yeah it\'ll be, this is it. i mean, this is it. it could feasibly be ever. i could be on tour with this... for a couple years at least, just this record',164 }, seb);165 await postTry(`/message/${channelId}`, {166 message: 'do you like the music you\'re playing?',167 }, mia);168 await postTry(`/message/${channelId}`, {169 message: 'i don\'t... i don\'t know what it matters',170 }, seb);171 await postTry(`/message/${channelId}`, {172 message: 'well, it matters because if you\'re gonna give up your dream, i think it matters that you like what you\'re playing on the road for years',173 }, mia);174 await postTry(`/message/${channelId}`, {175 message: 'do you like the music i\'m playing?',176 }, seb);177 await postTry(`/message/${channelId}`, {178 message: 'yeah, i do! i just didn\'t think that you did',179 }, mia);180 });...

Full Screen

Full Screen

print.js

Source:print.js Github

copy

Full Screen

1module.exports = {2 printHelp: function(bot, channelID) {3 bot.sendMessage({4 to: channelID,5 message:6 '!help: Shows commands\n' +7 '!join: Adds user into the queue to play\n' +8 '!leave: Removes user from the queue\n' +9 '!show: Displays all users currently in queue\n' +10 '!random: Makes random teams (Need 6 players)\n' +11 '!captains: Assigns two captains from the queue (Need 6 players)\n' +12 '!pick (number): Picks a player to a team if user is a captain\n' +13 '!teams: Shows teams\n' +14 '!draft (number): Captain only command to pick draft type (1 = linear, 2 = snake)'15 });16 },17 printClearMsg: function (bot, channelID) {18 bot.sendMessage({19 to: channelID,20 message: 'Queue has been cleared.'21 });22 },23 printEmptyQueue: function(bot, channelID) {24 bot.sendMessage({25 to: channelID,26 message: 'Queue is empty!'27 });28 },29 printCurrentQueueAfterUserLeave: function(bot, channelID, user, queue) {30 bot.sendMessage({31 to: channelID,32 message: user + ' has been removed from the queue. Current queue: ' + queue33 });34 },35 printUserNotInQueue: function(bot, channelID) {36 bot.sendMessage({37 to: channelID,38 message: 'User is not in queue!'39 });40 },41 printUserAlreadyInQueue: function(bot, channelID) {42 bot.sendMessage({43 to: channelID,44 message: 'User is already in the queue!'45 });46 },47 printCurrentQueue: function(bot, channelID, queue) {48 bot.sendMessage({49 to: channelID,50 message: 'Current Queue: ' + queue51 });52 },53 printCurrentQueueAfterUserJoin: function(bot, channelID, user, queue) {54 bot.sendMessage({55 to: channelID,56 message: user + ' has been added to the queue. Current queue: ' + queue57 });58 },59 printQueueIsFull: function(bot,channelID) {60 bot.sendMessage({61 to: channelID,62 message: 'Queue is full!'63 });64 },65 printRemainingPlayers: function(remainingPlayers) {66 let rp = '';67 for (let i = 0; i < remainingPlayers.length; i++){68 if (i === remainingPlayers.length - 1){69 rp += i+1 + '. ' + remainingPlayers[i];70 } else {71 rp += i+1 + '. ' + remainingPlayers[i] + ', ';72 }73 }74 return rp;75 },76 printTeamsAndRemaining: function(bot, channelID, blue, orange, remainingPlayers){77 bot.sendMessage({78 to: channelID,79 message: '```Orange Team: ' + orange + '\n' +80 'Blue Team: ' + blue + '```' +81 'Remaining Players: `' + this.printRemainingPlayers(remainingPlayers) + '`'82 });83 },84 printTeamsAndRemainingSnake: function(bot, channelID, blue, orange, remainingPlayers){85 bot.sendMessage({86 to: channelID,87 message: '```Blue pick again. \nOrange Team: ' + orange + '\n' +88 'Blue Team: ' + blue + '```' +89 'Remaining Players: `' + this.printRemainingPlayers(remainingPlayers) + '`'90 });91 },92 printTeamsAndLeftOut: function(bot, channelID, blue, orange, remainingPlayers){93 bot.sendMessage({94 to: channelID,95 message: '```Orange Team: ' + orange + '\n' + 'Blue Team: ' + blue + '```' +96 'Players sitting out: `' + this.printRemainingPlayers(remainingPlayers) + '`'97 });98 },99 printTeams: function(bot, channelID, blue, orange){100 bot.sendMessage({101 to: channelID,102 message: '```Orange Team: ' + orange + '\n' + 'Blue Team: ' + blue + '```'103 });104 },105 printNotEnoughPlayers: function(bot, channelID, queue) {106 bot.sendMessage({107 to: channelID,108 message: 'Not enough players in the queue! (' + queue.length + ')'109 });110 },111 printNotOnePlayerOnEachTeam: function(bot, channelID) {112 bot.sendMessage({113 to: channelID,114 message: 'There isn\'t at least one player on each team!'115 });116 },117 printCaptainsNotSelected: function(bot, channelID) {118 bot.sendMessage({119 to: channelID,120 message: 'Captains have not been selected!'121 });122 },123 printTeamsAreFull:function(bot, channelID) {124 bot.sendMessage({125 to: channelID,126 message: 'Teams have already been selected.'127 });128 },129 printNotCaptainOrNotTeamPick: function(bot, channelID) {130 bot.sendMessage({131 to: channelID,132 message: 'You are not a captain or it is not your teams pick.'133 });134 },135 printInvalidDraftType: function(bot, channelID) {136 bot.sendMessage({137 to: channelID,138 message: 'Not a valid draft type!'139 });140 },141 printInvalidPick: function(bot, channelID) {142 bot.sendMessage({143 to: channelID,144 message: 'Not a valid pick!'145 });146 },147 printSnakeDraftType: function(bot, channelID) {148 bot.sendMessage({149 to: channelID,150 message: 'Draft type is now snake.'151 });152 },153 printLinearDraftType: function(bot, channelID) {154 bot.sendMessage({155 to: channelID,156 message: 'Draft type is now linear.'157 });158 },159 printNotCaptain: function(bot, channelID) {160 bot.sendMessage({161 to: channelID,162 message: 'You are not a captain!'163 });164 }...

Full Screen

Full Screen

data2.js

Source:data2.js Github

copy

Full Screen

1var wauData1 = {2 meta: {3 product_id: 3,4 product_name: '兽血再燃', 5 refer: 'wau',6 title: '最近7天活跃用户数',7 8 dimensions: {9 ds: {name: '日期', type: 'str'},10 channelid: {name: '渠道', type: 'str'},11 },12 13 values: {14 value: {name: '周活跃用户数', type: 'int'}15 }16 },17 18 rows: [19 {ds: '2016-12-28', channelid: '309', value: 1070},20 {ds: '2016-12-28', channelid: '310', value: 1060},21 {ds: '2016-12-29', channelid: '309', value: 1090},22 {ds: '2016-12-29', channelid: '310', value: 990},23 {ds: '2016-12-30', channelid: '309', value: 4190},24 {ds: '2016-12-30', channelid: '310', value: 2190},25 {ds: '2016-12-31', channelid: '309', value: 7540},26 {ds: '2016-12-31', channelid: '310', value: 4540},27 ],28};29var wauData2 = {30 meta: {31 product_id: 3,32 product_name: '兽血再燃', 33 refer: 'wau',34 title: '最近7天活跃用户数',35 36 dimensions: {37 ds: {name: '日期', type: 'str'},38 channelid: {name: '渠道', type: 'str'},39 },40 41 values: {42 value: {name: '周活跃用户数', type: 'int'}43 }44 },45 46 rows: [47 {ds: '2016-12-28', channelid: '309', value: 1070},48 {ds: '2016-12-28', channelid: '310', value: 1060},49 {ds: '2017-12-29', channelid: '309', value: 1090},50 {ds: '2017-12-29', channelid: '310', value: 990},51 {ds: '2017-12-30', channelid: '309', value: 4190},52 {ds: '2017-12-30', channelid: '310', value: 2190},53 {ds: '2017-12-31', channelid: '309', value: 7540},54 {ds: '2017-12-31', channelid: '310', value: 4540},55 ],56};57var drruData1 = {58 meta: {59 product_id: 3,60 product_name: '兽血再燃', 61 refer: 'drru',62 title: '用户留存',63 64 dimensions: {65 ds: {name: '日期', type: 'str'},66 channelid: {name: '渠道', type: 'str'},67 lc_num: {name: '留存天数', type:'int'},68 },69 70 values: {71 value: {name: '留存人数', type: 'int'}72 }73 },74 75 rows: [76 {ds: '2016-12-28', channelid: '309', lc_num: 1, value: 70},77 {ds: '2016-12-28', channelid: '310', lc_num: 1, value: 60},78 {ds: '2016-12-29', channelid: '309', lc_num: 1, value: 90},79 {ds: '2016-12-29', channelid: '310', lc_num: 1, value: 99},80 {ds: '2016-12-30', channelid: '309', lc_num: 1, value: 90},81 {ds: '2016-12-30', channelid: '310', lc_num: 1, value: 21},82 {ds: '2016-12-31', channelid: '309', lc_num: 1, value: 75},83 {ds: '2016-12-31', channelid: '310', lc_num: 1, value: 45},84 ],85};86var drruData2 = {87 meta: {88 product_id: 3,89 product_name: '兽血再燃', 90 refer: 'drru',91 title: '用户留存',92 93 dimensions: {94 ds: {name: '日期', type: 'str'},95 channelid: {name: '渠道', type: 'str'},96 lc_num: {name: '留存天数', type:'int'},97 },98 99 values: {100 value: {name: '留存人数', type: 'int'}101 }102 },103 104 rows: [105 {ds: '2016-12-28', channelid: '309', lc_num: 2, value: 80},106 {ds: '2016-12-28', channelid: '310', lc_num: 2, value: 68},107 {ds: '2016-12-29', channelid: '309', lc_num: 2, value: 91},108 {ds: '2016-12-29', channelid: '310', lc_num: 2, value: 99},109 {ds: '2016-12-30', channelid: '309', lc_num: 2, value: 90},110 {ds: '2016-12-30', channelid: '310', lc_num: 2, value: 91},111 {ds: '2016-12-31', channelid: '309', lc_num: 2, value: 78},112 {ds: '2016-12-31', channelid: '310', lc_num: 2, value: 85},113 ],114};115var dnuDataByChannel = {116 meta: {117 product_id: 3,118 product_name: '兽血再燃', 119 refer: 'dnu',120 title: '新注册用户',121 122 dimensions: {123 ds: {name: '日期', type: 'str'},124 channelid: {name: '渠道', type: 'str'},125 },126 127 values: {128 value: {name: '注册人数', type: 'int'}129 }130 },131 132 rows: [133 {ds: '2016-12-28', channelid: '309', value: 180},134 {ds: '2016-12-28', channelid: '310', value: 168},135 {ds: '2016-12-29', channelid: '309', value: 191},136 {ds: '2016-12-29', channelid: '310', value: 199},137 {ds: '2016-12-30', channelid: '309', value: 190},138 {ds: '2016-12-30', channelid: '310', value: 191},139 {ds: '2016-12-31', channelid: '309', value: 178},140 {ds: '2016-12-31', channelid: '310', value: 185},141 ],142};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const { channelId } = page;7 console.log('Channel ID', channelId);8 await browser.close();9})();10I have tried this with the latest version of Playwright (v1.0.2) and it works as expected. Could you please try it with the latest version and let me know if you still face any issues?

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('text=Watch on YouTube');7 const page2 = await context.newPage();8 await page2.click('text=Watch on YouTube');9 const page3 = await context.newPage();10 await page3.click('text=Watch on YouTube');11 const page4 = await context.newPage();12 await page4.click('text=Watch on YouTube');13 const page5 = await context.newPage();14 await page5.click('text=Watch on YouTube');15 const page6 = await context.newPage();16 await page6.click('text=Watch on YouTube');17 const page7 = await context.newPage();18 await page7.click('text=Watch on YouTube');19 const page8 = await context.newPage();20 await page8.click('text=Watch on YouTube');21 const page9 = await context.newPage();22 await page9.click('text=Watch on YouTube');23 const page10 = await context.newPage();24 await page10.click('text=Watch on YouTube');25 const page11 = await context.newPage();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const channel = await page._channel;7 const id = await channel.channelId();8 console.log(id);9 await browser.close();10})();11from playwright.sync_api import sync_playwright12with sync_playwright() as p:13 browser = p.chromium.launch()14 context = browser.new_context()15 page = context.new_page()16 id = channel.channelId()17 print(id)18 browser.close()19import com.microsoft.playwright.*;20public class Test {21 public static void main(String[] args) {22 try (Playwright playwright = Playwright.create()) {23 BrowserType chromium = playwright.chromium();24 Browser browser = chromium.launch();25 BrowserContext context = browser.newContext();26 Page page = context.newPage();27 ChannelOwner channel = page._channel;28 String id = channel.channelId();29 System.out.println(id);30 browser.close();31 }32 }33}34using Microsoft.Playwright;35using Microsoft.Playwright.Transport.Channels;36using Microsoft.Playwright.Transport.Protocol;37using System;38using System.Threading.Tasks;39{40 {41 static async Task Main(string[] args)42 {43 using var playwright = await Playwright.CreateAsync();44 var chromium = playwright.Chromium;45 var browser = await chromium.LaunchAsync();46 var context = await browser.NewContextAsync();47 var page = await context.NewPageAsync();48 ChannelOwner channel = page._channel;49 string id = channel.ChannelId();50 Console.WriteLine(id);51 await browser.CloseAsync();52 }53 }54}55import (56func main() {57 pw, err := playwright.Run()58 if err != nil {59 log.Fatalf("could not start playwright: %v", err)60 }61 browser, err := pw.Chromium.Launch()

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium, webkit, firefox} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const channelId = await page._channelId;7 console.log(channelId);8 await browser.close();9})();10const {chromium, webkit, firefox} = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const channelId = await page._channelId;16 const browserId = parseInt(channelId.split('_')[1]);17 console.log(browserId);18 await browser.close();19})();20const {chromium, webkit, firefox} = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 const channelId = await page._channelId;26 const browserId = parseInt(channelId.split('_')[1]);

Full Screen

Using AI Code Generation

copy

Full Screen

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

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const { channelId } = page;7 console.log(channelId);8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 const { channelId } = page;16 const connection = await browser._connection;17 const browserObject = await connection.browser(channelId);18 console.log(browserObject);19 await browser.close();20})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const channel = await page._channel;7 const channelId = channel._guid;8 console.log(channelId);9 await browser.close();10})();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 const channel = await page._channel;17 const channelId = channel._guid;18 console.log(channelId);19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch();24 const context = await browser.newContext();25 const page = await context.newPage();26 const channel = await page._channel;27 const channelId = channel._guid;28 console.log(channelId);29 await browser.close();30})();31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch();34 const context = await browser.newContext();35 const page = await context.newPage();36 const channel = await page._channel;37 const channelId = channel._guid;38 console.log(channelId);39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();46 const channel = await page._channel;47 const channelId = channel._guid;48 console.log(channelId);49 await browser.close();50})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const channelId = await page._delegate.channelId();7 console.log(channelId);8 await browser.close();9})();10const { chromium } = require('playwright');11const { Connection } = require('playwright-channel');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 const channelId = await page._delegate.channelId();17 const connection = new Connection();18 await connection.connect();19 const browserChannel = connection.rootObject().browser(channelId);20 await browserChannel.close();21 await browser.close();22})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 const { channelId } = browser._initializer;8 console.log(channelId);9 await browser.close();10})();11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch({14 });15 const context = await browser.newContext();16 const page = await context.newPage();17 const { channelId } = browser._initializer;18 console.log(channelId);19 await browser.close();20})();21const { chromium } = require('playwright');22(async () => {23 const browser = await chromium.launch({24 });25 const context = await browser.newContext();26 const page = await context.newPage();27 const { channelId } = browser._initializer;28 console.log(channelId);29 await browser.close();30})();31const { chromium } = require('playwright');32(async () => {33 const browser = await chromium.launch({34 });35 const context = await browser.newContext();36 const page = await context.newPage();37 const { channelId } = browser._initializer;38 console.log(channelId);39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch({44 });

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({4 });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.waitForSelector('text=Search');8 await page.click('text=Search');9 await page.waitForSelector('input[aria-label="Search"]');10 await page.fill('input[aria-label="Search"]', 'playwright');11 await page.keyboard.press('Enter');12 await page.waitForSelector('text=Playwright - Browser automation library for Node.js');13 await page.click('text=Playwright - Browser automation library for Node.js');14 await page.waitForSelector('text=Playwright');15 await page.click('text=Playwright');16 const targetId = await page.evaluate(() => {17 return window.opener.targetId;18 });19 await page.close();20 const newPage = await context.newPage({21 });22 await newPage.waitForLoadState('networkidle');23 const channelPage = await newPage.evaluate(() => {24 return window.location.href;25 });26 console.log(channelPage);27 await newPage.close();28 await browser.close();29})();

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