type
stringclasses
7 values
content
stringlengths
4
9.55k
repo
stringlengths
7
96
path
stringlengths
4
178
language
stringclasses
1 value
ArrowFunction
(): Promise<string> => getParameter("ist-id")
shuymn/iidx-routine
src/lib/secrets.ts
TypeScript
ArrowFunction
(): Promise<string> => getParameter("ist-password")
shuymn/iidx-routine
src/lib/secrets.ts
TypeScript
ArrowFunction
(): Promise<string> => getParameter("cpi-id")
shuymn/iidx-routine
src/lib/secrets.ts
TypeScript
ArrowFunction
(): Promise<string> => getParameter("cpi-password")
shuymn/iidx-routine
src/lib/secrets.ts
TypeScript
ClassDeclaration
export class Auth { private _model: MongoModel; private _create: Function; private _findall: Function; private _findone: Function; private _update: Function; private _delete: Function; constructor ( model: MongoModel, verify: Function, no_token_for: Array<string> ) { this._model = model; let self = this; this._create = function (request: any, response: any, next: any) { if (no_token_for.includes("CREATE")) { next(); } else { const token = request.headers['access-token']; if (token) { verify(token, request.body, "CREATE", null) .then(function(verified: boolean) { if(verified) { next(); } else { response.sendStatus(401); } }).catch(function(error: any) { response.sendStatus(401); }); } else { response.sendStatus(401); } } }; this._findall = function (request: any, response: any, next: any) { if (no_token_for.includes("FINDALL")) { next(); } else { const token = request.headers['access-token']; if (token) { verify(token, request.body, "FINDALL", null) .then(function(verified: boolean) { if(verified) { next(); } else { response.sendStatus(401); } }).catch(function(error: any) { response.sendStatus(401); }); } else { response.sendStatus(401); } } }; this._findone = function (request: any, response: any, next: any) { if (no_token_for.includes("FINDONE")) { next(); } else { const token = request.headers['access-token']; const instance_id = request.params[`${self._model.name}id`] if (token) { verify(token, request.body, "FINDONE", instance_id) .then(function(verified: boolean) { if(verified) { next(); } else { response.sendStatus(401); } }).catch(function(error: any) { response.sendStatus(401); }); } else { response.sendStatus(401); } } }; this._update = function (request: any, response: any, next: any) { if (no_token_for.includes("UPDATE")) { next(); } else { const token = request.headers['access-token']; const instance_id = request.params[`${self._model.name}id`] if (token) { verify(token, request.body, "UPDATE", instance_id) .then(function(verified: boolean) { if(verified) { next(); } else { response.sendStatus(401); } }).catch(function(error: any) { response.sendStatus(401); }); } else { response.sendStatus(401); } } }; this._delete = function (request: any, response: any, next: any) { if (no_token_for.includes("DELETE")) { next(); } else { const token = request.headers['access-token']; const instance_id = request.params[`${self._model.name}id`] if (token) { verify(token, request.body, "DELETE", instance_id) .then(function(verified: boolean) { if(verified) { next(); } else { response.sendStatus(401); } }).catch(function(error: any) { response.sendStatus(401); }); } else { response.sendStatus(401); } } }; } public get create(): Function { return this._create; } public get findall(): Function { return this._findall; } public get findone(): Function { return this._findone; } public get update(): Function { return this._update; } public get delete(): Function { return this._delete; } }
The-Gray-Hole/rest-mongoose
src/auth.ts
TypeScript
InterfaceDeclaration
export interface IWebRequest { body: any; weixin: any; headers: { [name: string]: string, }; on(event: string, ...args: any[]): void; }
crisboarna/botbuilder-wechat-connector-ts
src/interfaces/IWeb.ts
TypeScript
InterfaceDeclaration
export interface IWebResponse { end(): this; send(status: number, body?: any): this; send(body: any): this; status(code: number): this; }
crisboarna/botbuilder-wechat-connector-ts
src/interfaces/IWeb.ts
TypeScript
ArrowFunction
() => ( <ViewListItem viewId="viewListItem1"
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
ArrowFunction
() => ( <ViewListItem viewId="invalidViewListItem"
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
MethodDeclaration
text('viewName', viewName)
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
MethodDeclaration
text('viewDescription', viewDescription)
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
MethodDeclaration
text('icon', null)
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
MethodDeclaration
text('deleteText', deleteText)
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
MethodDeclaration
text('editText', editText)
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
MethodDeclaration
text('editTip', editTip)
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
MethodDeclaration
action(deleteActionText)
Delawen/syndesis
app/ui-react/packages/ui/stories/Data/Views/ViewListItem.stories.tsx
TypeScript
FunctionDeclaration
function loadTestFixture(fileName: string): Promise<string> { return fs.readFile(path.join(__dirname, 'test-fixtures', fileName), 'utf-8'); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
() => { describe('parseProducts', () => { it('single product with a single variant', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('single-product-single-variant.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('single product with a multiple variants', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('single-product-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('multiple products with multiple variants', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('multiple-products-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('custom fields', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('custom-fields.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('works with streamed input', async () => { const importParser = new ImportParser(); const filename = path.join(__dirname, 'test-fixtures', 'multiple-products-multiple-variants.csv'); const input = fs.createReadStream(filename); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); describe('error conditions', () => { it('reports errors on invalid option values', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-option-values.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'The number of optionValues must match the number of optionGroups on line 2', 'The number of optionValues must match the number of optionGroups on line 3', 'The number of optionValues must match the number of optionGroups on line 4', 'The number of optionValues must match the number of optionGroups on line 5', ]); }); it('reports error on ivalid columns', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-columns.csv'); const result = await importParser.parseProducts(input); expect(result.results).toEqual([]); expect(result.errors).toEqual([ 'The import file is missing the following columns: "slug", "assets", "variantFacets"', ]); }); it('reports error on ivalid row length', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-row-length.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'Invalid Record Length: header length is 14, got 12 on line 3', 'Invalid Record Length: header length is 14, got 1 on line 4', ]); expect(result.results.length).toBe(2); }); }); }); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
() => { it('single product with a single variant', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('single-product-single-variant.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('single product with a multiple variants', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('single-product-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('multiple products with multiple variants', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('multiple-products-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('custom fields', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('custom-fields.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); it('works with streamed input', async () => { const importParser = new ImportParser(); const filename = path.join(__dirname, 'test-fixtures', 'multiple-products-multiple-variants.csv'); const input = fs.createReadStream(filename); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }); describe('error conditions', () => { it('reports errors on invalid option values', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-option-values.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'The number of optionValues must match the number of optionGroups on line 2', 'The number of optionValues must match the number of optionGroups on line 3', 'The number of optionValues must match the number of optionGroups on line 4', 'The number of optionValues must match the number of optionGroups on line 5', ]); }); it('reports error on ivalid columns', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-columns.csv'); const result = await importParser.parseProducts(input); expect(result.results).toEqual([]); expect(result.errors).toEqual([ 'The import file is missing the following columns: "slug", "assets", "variantFacets"', ]); }); it('reports error on ivalid row length', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-row-length.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'Invalid Record Length: header length is 14, got 12 on line 3', 'Invalid Record Length: header length is 14, got 1 on line 4', ]); expect(result.results.length).toBe(2); }); }); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const input = await loadTestFixture('single-product-single-variant.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const input = await loadTestFixture('single-product-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const input = await loadTestFixture('multiple-products-multiple-variants.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const input = await loadTestFixture('custom-fields.csv'); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const filename = path.join(__dirname, 'test-fixtures', 'multiple-products-multiple-variants.csv'); const input = fs.createReadStream(filename); const result = await importParser.parseProducts(input); expect(result.results).toMatchSnapshot(); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
() => { it('reports errors on invalid option values', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-option-values.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'The number of optionValues must match the number of optionGroups on line 2', 'The number of optionValues must match the number of optionGroups on line 3', 'The number of optionValues must match the number of optionGroups on line 4', 'The number of optionValues must match the number of optionGroups on line 5', ]); }); it('reports error on ivalid columns', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-columns.csv'); const result = await importParser.parseProducts(input); expect(result.results).toEqual([]); expect(result.errors).toEqual([ 'The import file is missing the following columns: "slug", "assets", "variantFacets"', ]); }); it('reports error on ivalid row length', async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-row-length.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'Invalid Record Length: header length is 14, got 12 on line 3', 'Invalid Record Length: header length is 14, got 1 on line 4', ]); expect(result.results.length).toBe(2); }); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-option-values.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'The number of optionValues must match the number of optionGroups on line 2', 'The number of optionValues must match the number of optionGroups on line 3', 'The number of optionValues must match the number of optionGroups on line 4', 'The number of optionValues must match the number of optionGroups on line 5', ]); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-columns.csv'); const result = await importParser.parseProducts(input); expect(result.results).toEqual([]); expect(result.errors).toEqual([ 'The import file is missing the following columns: "slug", "assets", "variantFacets"', ]); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
ArrowFunction
async () => { const importParser = new ImportParser(); const input = await loadTestFixture('invalid-row-length.csv'); const result = await importParser.parseProducts(input); expect(result.errors).toEqual([ 'Invalid Record Length: header length is 14, got 12 on line 3', 'Invalid Record Length: header length is 14, got 1 on line 4', ]); expect(result.results.length).toBe(2); }
AneBLucena/vendure
packages/core/src/data-import/providers/import-parser/import-parser.spec.ts
TypeScript
InterfaceDeclaration
export interface ArgError { path: string[] id?: string error: InvalidArgError }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface FieldError { path: string[] error: InvalidFieldError }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface InvalidFieldTypeError { type: 'invalidFieldType' modelName: string fieldName: string providedValue: any }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface InvalidFieldNameError { type: 'invalidFieldName' modelName: string didYouMean?: string | null providedName: string isInclude?: boolean isIncludeScalar?: boolean outputType: DMMF.OutputType }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface EmptySelectError { type: 'emptySelect' field: DMMF.SchemaField }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface EmptyIncludeError { type: 'emptyInclude' field: DMMF.SchemaField }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface NoTrueSelectError { type: 'noTrueSelect' field: DMMF.SchemaField }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface IncludeAndSelectError { type: 'includeAndSelect' field: DMMF.SchemaField }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
/** * This error occurs if the user provides an arg name that doens't exist */ export interface InvalidArgNameError { type: 'invalidName' providedName: string providedValue: any didYouMeanArg?: string // if the possible names are too different and therefore just arbitrary, we don't suggest anything didYouMeanField?: string // if it's very similar to a field, they probably just forgot the select statement originalType: DMMF.ArgType possibilities?: DMMF.SchemaArgInputType[] outputType?: DMMF.OutputType }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
/** * Opposite of InvalidArgNameError - if the user *doesn't* provide an arg that should be provided * This error both happens with an implicit and explicit `undefined` */ export interface MissingArgError { type: 'missingArg' missingName: string missingArg: DMMF.SchemaArg // context of the schema arg to show a nice error atLeastOne: boolean atMostOne: boolean }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
/** * If a user incorrectly provided null where she shouldn't have */ export interface InvalidNullArgError { type: 'invalidNullArg' name: string invalidType: DMMF.SchemaArgInputType[] // note that this could be an object or scalar type. in the object case, we print the whole object type atLeastOne: boolean atMostOne: boolean }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface AtMostOneError { type: 'atMostOne' key: string inputType: DMMF.InputType providedKeys: string[] }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
export interface AtLeastOneError { type: 'atLeastOne' key: string inputType: DMMF.InputType }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
InterfaceDeclaration
/** * If the scalar type of an arg is not matching what is required */ export interface InvalidArgTypeError { type: 'invalidType' argName: string requiredType: { bestFittingType: DMMF.SchemaArgInputType inputType: DMMF.SchemaArgInputType[] } providedValue: any }
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
TypeAliasDeclaration
export type InvalidFieldError = | InvalidFieldNameError | InvalidFieldTypeError | EmptySelectError | NoTrueSelectError | IncludeAndSelectError | EmptyIncludeError
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
TypeAliasDeclaration
export type JavaScriptPrimitiveType = 'number' | 'string' | 'boolean'
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
TypeAliasDeclaration
export type InvalidArgError = | InvalidArgNameError | MissingArgError | InvalidArgTypeError | AtLeastOneError | AtMostOneError | InvalidNullArgError
Adapt-API/prisma
packages/client/src/runtime/error-types.ts
TypeScript
ArrowFunction
({ redirectTo, claims, roles, element, children, }: IPrivateRouteProps) => { const keycloak = useKeycloakWrapper(); if (!keycloak.authenticated) { return <Navigate to={redirectTo} />; } else if ((!!claims && !keycloak.hasClaim(claims)) || (!!roles && !keycloak.hasRole(roles))) { return <div>ERROR</div>; } return element ? element : <>{children}</>; }
ckayfish/tno
app/editor/src/features/router/PrivateRoute.tsx
TypeScript
InterfaceDeclaration
/** * PrivateRoute properties. */ interface IPrivateRouteProps { /** * The path to redirect to if user is unauthorized. */ redirectTo: string; /** * A role the user belongs to. */ roles?: Role | Array<Role>; /** * A claim the user has. */ claims?: Claim | Array<Claim>; /** * The element to load if authorized. */ element?: React.ReactElement | null; /** * The children elements to load if authorized. */ children?: React.ReactNode; }
ckayfish/tno
app/editor/src/features/router/PrivateRoute.tsx
TypeScript
FunctionDeclaration
export async function up(knex: Knex) { return knex.schema.createTable('connections', table => { table.increments('id').primary(); table.integer('user_id') .notNullable() .references('id') .inTable('users') .onUpdate('CASCADE') .onDelete('CASCADE'); table.timestamp('created_at') .defaultTo(knex.raw('CURRENT_TIMESTAMP')) .notNullable(); }); }
gmmunis/Proffy
server/src/database/migrations/03_create_connection.ts
TypeScript
FunctionDeclaration
export async function down(knex: Knex) { return knex.schema.dropTable('connections'); }
gmmunis/Proffy
server/src/database/migrations/03_create_connection.ts
TypeScript
ArrowFunction
table => { table.increments('id').primary(); table.integer('user_id') .notNullable() .references('id') .inTable('users') .onUpdate('CASCADE') .onDelete('CASCADE'); table.timestamp('created_at') .defaultTo(knex.raw('CURRENT_TIMESTAMP')) .notNullable(); }
gmmunis/Proffy
server/src/database/migrations/03_create_connection.ts
TypeScript
ClassDeclaration
export class CreateDTO { @IsString() @IsNotEmpty() name: string; @IsEmail() @IsNotEmpty() email: string; @IsString() @IsNotEmpty() password: string; }
avidianity/garden-gnome
server/src/app/user/dto/create.dto.ts
TypeScript
ArrowFunction
(device: MediaDeviceInfo) => { switch (device.kind) { case 'audioinput': microphones[device.deviceId] = device.label || 'Microphone ' + (++n); break; case 'audiooutput': speakers[device.deviceId] = device.label || 'Speaker ' + (++k); break; case 'videoinput': webcams[device.deviceId] = device.label || 'Camera ' + (++c); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
(resolve, reject) => { chrome.runtime.sendMessage(CHROME_EXTENSION_ID, {type: 'PYCHAT_SCREEN_SHARE_REQUEST'}, resolve); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
() => { if (!this.callInfo.showMic) { return; } if (audioProc.volumeValuesCount < 101) { audioProc.prevVolumeValues += getAverageAudioLevel(audioProc); audioProc.volumeValuesCount++; if (audioProc.volumeValuesCount === 100 && audioProc.prevVolumeValues === 0) { let url = isChrome ? 'setting in chrome://settings/content' : 'your browser settings'; url += navigator.platform.indexOf('Linux') >= 0 ? '. Open pavucontrol for more info' : ' . Right click on volume icon in system tray -> record devices -> input -> microphone'; this.store.growlError(`Unable to capture input from microphone. Check your microphone connection or ${url}`); } } const payload: NumberIdentifier = { id: this.roomId, state: Math.sqrt(getAverageAudioLevel(audioProc)) }; this.store.setCurrentMicLevel(payload); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
wsId => parseInt(wsId.split(":")[0], 10) != userId
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
(e) => { const message: ConnectToRemoteMessage = { action: 'connectToRemote', stream: this.localStream, handler: Subscription.getPeerConnectionId(this.connectionId!, e) }; sub.notify(message); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
(resolve, reject) => { const error = {rawError: `To share your screen you need chrome extension.<b> <a href="${CHROME_EXTENSION_URL}" target="_blank">Click to install</a></b>`}; if (chrome.runtime && chrome.runtime.sendMessage) { let triggered = false; const timedCB = setTimeout(function () { !triggered && reject(error); triggered = true; }, 500); chrome.runtime.sendMessage(CHROME_EXTENSION_ID, { type: 'PYCHAT_SCREEN_SHARE_PING' }, (response) => { if (triggered) { this.logger.error('extension responded after timeout')(); } else if (response && response.data === 'success') { clearTimeout(timedCB); resolve(); } else { clearTimeout(timedCB); reject(response && response.data || error); } }); } else { reject(error); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
(response) => { if (triggered) { this.logger.error('extension responded after timeout')(); } else if (response && response.data === 'success') { clearTimeout(timedCB); resolve(); } else { clearTimeout(timedCB); reject(response && response.data || error); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
s => { if (s) { if (!stream) { stream = s; } else { for (let t of s.getTracks()) { stream.addTrack(t); } } } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public checkTransferDestroy(payload: CheckTransferDestroy) { this.removeOpponent(payload.wsOpponentId); super.checkTransferDestroy(payload); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public inflateDevices(devices: MediaDeviceInfo[]): void { let n: number, k: number, c: number = 0; const microphones: { [id: string]: string } = {}; const speakers: { [id: string]: string } = {}; const webcams: { [id: string]: string } = {}; const payload: SetDevices = { microphones, webcams, speakers, roomId: this.roomId }; if (devices) { devices.forEach((device: MediaDeviceInfo) => { switch (device.kind) { case 'audioinput': microphones[device.deviceId] = device.label || 'Microphone ' + (++n); break; case 'audiooutput': speakers[device.deviceId] = device.label || 'Speaker ' + (++k); break; case 'videoinput': webcams[device.deviceId] = device.label || 'Camera ' + (++c); } }); } this.store.setDevices(payload); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public getConnectionId(): string | null { return this.connectionId; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public acceptCall(message: AcceptCallMessage) { if (this.callStatus !== 'received_offer') { // if we're call initiator if (!this.connectionId) { throw Error('Conn is is null'); } const payload: ConnectToRemoteMessage = { action: 'connectToRemote', handler: Subscription.getPeerConnectionId(this.connectionId, message.opponentWsId), stream: this.localStream }; sub.notify(payload); } else { this.acceptedPeers.push(message.opponentWsId); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public async getDesktopShareFromExtension(): Promise<string> { if (!isChrome) { throw new Error('ScreenCast feature is only available from chrome atm'); } else if (isMobile) { throw new Error('ScreenCast is not available for mobile phones yet'); } else { await this.pingExtension(); this.logger.log('Ping to extension succeeded')(); const response = await new Promise<{streamId: string; data: string}>((resolve, reject) => { chrome.runtime.sendMessage(CHROME_EXTENSION_ID, {type: 'PYCHAT_SCREEN_SHARE_REQUEST'}, resolve); }); if (response && response.data === 'success') { this.logger.log('Getting desktop share succeeded')(); return response.streamId; } else { throw new Error('Failed to capture desktop stream'); } } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public async captureInput(): Promise<MediaStream|null> { this.logger.debug('capturing input')(); // start // we can't await promise one by one // because 2nd promise would be called after some period of time // which would destroy user gesture Event. // and browsers like safari won't let capture userMedia w/o existing user gesture let micPromise = this.captureMic(); let shareScreenPromise = this.captureScreenShare(); let painterPromise = this.capturePainterShare(); // end let streams: (MediaStream|null)[] = await Promise.all([micPromise, shareScreenPromise, painterPromise]); let stream = this.combineStreams(...streams) return stream; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public processAudio(audioProc: JsAudioAnalyzer) { return () => { if (!this.callInfo.showMic) { return; } if (audioProc.volumeValuesCount < 101) { audioProc.prevVolumeValues += getAverageAudioLevel(audioProc); audioProc.volumeValuesCount++; if (audioProc.volumeValuesCount === 100 && audioProc.prevVolumeValues === 0) { let url = isChrome ? 'setting in chrome://settings/content' : 'your browser settings'; url += navigator.platform.indexOf('Linux') >= 0 ? '. Open pavucontrol for more info' : ' . Right click on volume icon in system tray -> record devices -> input -> microphone'; this.store.growlError(`Unable to capture input from microphone. Check your microphone connection or ${url}`); } } const payload: NumberIdentifier = { id: this.roomId, state: Math.sqrt(getAverageAudioLevel(audioProc)) }; this.store.setCurrentMicLevel(payload); }; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
setCanvasElement(canvas: HTMLCanvasElement) { this.logger.debug('Setting canvas to {}', canvas)(); this.canvas = canvas; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public async toggleDevice(videoType: VideoType) { const track = this.getTrack(videoType); if (track && track.readyState === 'live') { this.logger.log('toggleDevice')(); let state = false; if (videoType === VideoType.AUDIO) { state = this.callInfo.showMic; } else if (videoType === VideoType.SHARE) { state = this.callInfo.shareScreen; } else if (videoType === VideoType.VIDEO) { state = this.callInfo.showVideo; } else if (videoType === VideoType.PAINT) { state = this.callInfo.sharePaint; } track.enabled = state; } else { await this.updateConnection(); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public async updateConnection() { this.logger.log('updateConnection')(); let stream: MediaStream|null = null; // TODO I removed this if below because otherwise if we created a connection w/o stream (no audio/ web/ share screen) we won't be able to add it in future // find out why this was necessary // if (this.localStream?.active) { try { stream = await this.captureInput(); this.stopLocalStream(); this.attachLocalStream(stream); const message: ChangeStreamMessage = { handler: Subscription.allPeerConnectionsForTransfer(this.connectionId!), action: 'streamChanged', allowZeroSubscribers: true, newStream: stream!, }; sub.notify(message) } catch (e) { this.handleStream(e, stream); } // } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public getTrack(kind: VideoType) { // TODO let track = null; let tracks = []; if (this.localStream) { if (kind === VideoType.VIDEO || kind === VideoType.SHARE || kind === VideoType.PAINT) { tracks = this.localStream.getVideoTracks(); } else if (kind === VideoType.AUDIO) { tracks = this.localStream.getAudioTracks(); } else { throw Error('invalid track name'); } if (tracks.length > 0) { const isShare = tracks[0].isShare; const isCanvas = tracks[0].isCanvas; if (isShare && kind === VideoType.SHARE) { track = tracks[0]; } if (isCanvas && kind === VideoType.PAINT) { track = tracks[0]; } else if (!isShare && !isCanvas && kind === VideoType.VIDEO) { track = tracks[0]; } else if (kind === VideoType.AUDIO) { track = tracks[0]; } } } return track; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
// setAudio(value) { // let audioTrack = this.getTrack('audio'); // if (!audioTrack) { // let payload: BooleanIdentifier = { // id: this.roomId, // state: false, // }; // this.store.setMicToState(payload); // } // } public setCallIconsState() { // if (this.callInfo.showMic) { // let audioTrack = this.getTrack('audio'); // if (!audioTrack) { // let payload: BooleanIdentifier = { // id: this.roomId, // state: false, // } // this.store.setMicToState(payload); // } // } // let videoTrack = this.getTrack('video'); // if (this.) // this.setVideo(videoTrack && videoTrack.enabled); // this.setAudio(audioTrack && audioTrack.enabled); // this.setDesktopCapture(this.getTrack('share') != null); // this.autoSetLocalVideoVisibility(); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public async offerCall() { let stream: MediaStream | null = null; try { stream = await this.captureInput(); this.logger.log('got local stream {}', stream)(); if (stream) { this.attachLocalStream(stream); } const payload: BooleanIdentifier = { state: true, id: this.roomId }; this.setCallStatus('sent_offer'); this.store.setCallActiveToState(payload); let e = await this.wsHandler.offerCall(this.roomId, browserVersion); this.setConnectionId(e.connId); } catch (e) { this.handleStream(e, stream); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public createCallPeerConnection({ opponentWsId, userId }: { opponentWsId: string; userId: number }) { if (sub.getNumberOfSubscribers(Subscription.getPeerConnectionId(this.connectionId!, opponentWsId)) !== 0) { this.logger.warn(`Peer connection ${opponentWsId} won't be created as it's already exists`)(); return } if (opponentWsId > this.wsHandler.getWsConnectionId()) { new CallSenderPeerConnection(this.roomId, this.connectionId!, opponentWsId, userId, this.wsHandler, this.store); } else { new CallReceiverPeerConnection(this.roomId, this.connectionId!, opponentWsId, userId, this.wsHandler, this.store); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
protected setConnectionId(connId: string | null) { if (this.connectionId ) { if (!connId) { sub.unsubscribe(Subscription.getTransferId(this.connectionId), this) } else { this.logger.error('Received new connectionId while old one stil exists')(); } } if (this.connectionId !== connId && connId) { sub.subscribe(Subscription.getTransferId(connId), this); } super.setConnectionId(connId); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public addOpponent(connId: string, userId: number, opponentWsId: string): void { this.logger.debug(`Adding opponent ${connId} ${userId} ${opponentWsId}`)(); this.setConnectionId(connId); this.acceptedPeers.push(opponentWsId); this.createCallPeerConnection({opponentWsId, userId}); this.store.setCallActiveButNotJoinedYet({state: true, id: this.roomId}); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public removeUserOpponent(userId: number): void { this.acceptedPeers = this.acceptedPeers.filter(wsId => parseInt(wsId.split(":")[0], 10) != userId); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public removeOpponent(opponentWsId: string): void { let index = this.acceptedPeers.indexOf(opponentWsId); if (index >= 0) { this.acceptedPeers.splice(index); } if (this.acceptedPeers.length === 0) { this.store.setCallActiveButNotJoinedYet({state: false, id: this.roomId}); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public replyCall(message: ReplyCallMessage) { this.createCallPeerConnection(message); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public initAndDisplayOffer(message: OfferCall) { this.setCallStatus('received_offer'); if (this.connectionId) { this.logger.error('Old connId still exists {}', this.connectionId)(); } this.setConnectionId(message.connId); this.logger.log('CallHandler initialized')(); this.wsHandler.replyCall(message.connId, browserVersion); const payload2: IncomingCallModel = { connId: message.connId, roomId: message.roomId, userId: message.userId }; this.acceptedPeers.push(message.opponentWsId); this.store.setIncomingCall(payload2); this.createCallPeerConnection(message); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public answerCall() { this.doAnswer(false); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public async doAnswer(withVideo: boolean) { this.store.setIncomingCall(null); this.store.setCallActiveToState({ id: this.roomId, state: true }); this.store.setVideoToState({ type: 'webcam', id: this.roomId, state: withVideo }); this.store.setMicToState({ id: this.roomId, state: true }); this.setCallStatus('accepted'); const stream = await this.captureInput(); this.attachLocalStream(stream); this.wsHandler.acceptCall(this.connectionId!); this.connectToRemote(); let message1: RouterNavigateMessage = { handler: 'router', action: 'navigate', to: `/chat/${this.roomId}` }; sub.notify(message1); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public async joinCall() { this.store.setCallActiveButNotJoinedYet({ id: this.roomId, state: false }); this.store.setCallActiveToState({ id: this.roomId, state: true }); this.setCallStatus('accepted'); const stream = await this.captureInput(); this.attachLocalStream(stream); this.wsHandler.joinCall(this.connectionId!); this.connectToRemote(); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private connectToRemote() { this.acceptedPeers.forEach((e) => { const message: ConnectToRemoteMessage = { action: 'connectToRemote', stream: this.localStream, handler: Subscription.getPeerConnectionId(this.connectionId!, e) }; sub.notify(message); }); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public videoAnswerCall() { this.doAnswer(true); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public destroyAudioProcessor() { if (this.audioProcessor ) { removeAudioProcesssor(this.audioProcessor!); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public stopLocalStream() { this.destroyAudioProcessor(); stopVideo(this.localStream); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public onDestroy() { this.stopLocalStream(); const payload2: MediaIdentifier = { id: this.roomId, media: null }; this.store.setLocalStreamSrc(payload2); this.setConnectionId(null); const payload: BooleanIdentifier = { state: false, id: this.roomId }; this.store.setCallActiveToState(payload); this.store.setCallActiveButNotJoinedYet({ id: this.roomId, state: false }); this.acceptedPeers.length = 0; // = [] }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public declineCall() { this.store.setIncomingCall(null); this.wsHandler.destroyCallConnection(this.connectionId!, 'decline'); this.onDestroy(); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
public hangCall() { this.logger.debug('on hangCall called')(); if (this.connectionId) { this.wsHandler.destroyCallConnection(this.connectionId!, 'hangup'); } else { this.logger.warn('Current call doesnt have conenctionId yet, skipping hangup')(); } const hadConnections = this.connectionId && sub.getNumberOfSubscribers(Subscription.allPeerConnectionsForTransfer(this.connectionId!)) > 0; if (hadConnections) { if (!this.connectionId) { this.logger.error(`Can't close connections since it's null`)(); return; } let message: DestroyPeerConnectionMessage = { action: 'destroy', handler: Subscription.allPeerConnectionsForTransfer(this.connectionId!), allowZeroSubscribers: true }; sub.notify(message); } else { this.onDestroy(); } }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private async pingExtension(): Promise<void> { return new Promise<void>((resolve, reject) => { const error = {rawError: `To share your screen you need chrome extension.<b> <a href="${CHROME_EXTENSION_URL}" target="_blank">Click to install</a></b>`}; if (chrome.runtime && chrome.runtime.sendMessage) { let triggered = false; const timedCB = setTimeout(function () { !triggered && reject(error); triggered = true; }, 500); chrome.runtime.sendMessage(CHROME_EXTENSION_ID, { type: 'PYCHAT_SCREEN_SHARE_PING' }, (response) => { if (triggered) { this.logger.error('extension responded after timeout')(); } else if (response && response.data === 'success') { clearTimeout(timedCB); resolve(); } else { clearTimeout(timedCB); reject(response && response.data || error); } }); } else { reject(error); } }); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private async captureMic(): Promise<MediaStream|null> { let stream: MediaStream|null = null; let showMic = this.callInfo.showMic; let showVideo = this.callInfo.showVideo; if (showMic || showVideo) { // inflate devices b4 capture, in this case we can disable video if user enabled it but has no webcam if (navigator.mediaDevices.enumerateDevices) { const devices: MediaDeviceInfo[] = await navigator.mediaDevices.enumerateDevices(); this.inflateDevices(devices); if (showMic !== this.callInfo.showMic) { this.store.growlError("Unable to capture audio, because no microphones found") } if (showVideo !== this.callInfo.showVideo) { this.store.growlError("Unable to capture video, because no webcam found") } if (!this.callInfo.showMic && !this.callInfo.showVideo) { return null; //inflate devices could have set them to null if they are absent } } let audio: any = this.callInfo.showMic; if (this.callInfo.currentMic && audio) { audio = {deviceId: this.callInfo.currentMic}; } let video: any = this.callInfo.showVideo; // convert null to bolean, if we pass null to getUserMedia it tries to capture if (this.callInfo.currentWebcam && video) { video = {deviceId: this.callInfo.currentWebcam}; } this.logger.debug('navigator.mediaDevices.getUserMedia({audio, video})')(); stream = await navigator.mediaDevices.getUserMedia({audio, video}); this.logger.debug('navigator.mediaDevices.getUserMedia({audio, video})')(); if (!stream) { throw new Error('Unable to capture stream'); } } return stream; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private async capturePainterShare(): Promise<MediaStream|null> { if (this.callInfo.sharePaint) { // TODO install definitely type // @ts-expect-error if (!this.canvas.captureStream) { throw Error('Current browser doesn\'t support canvas stream'); } // @ts-expect-error let stream = this.canvas.captureStream(); const tracks: any[] = stream.getVideoTracks(); if (!(tracks && tracks.length > 0)) { throw Error('No video tracks from captured from canvas'); } tracks[0].isCanvas = true; return stream; } return null; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private async captureScreenShare(): Promise<MediaStream|null> { let stream: MediaStream|null = null; if (this.callInfo.shareScreen) { const chromeVersion = getChromeVersion(); if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) { this.logger.debug('Getting shareScreen from navigator.getDisplayMedia')(); stream = await navigator.mediaDevices.getDisplayMedia({video: true}); } else { if (chromeVersion && chromeVersion > 70) { this.store.growlInfo('You can now use chrome://flags/#enable-experimental-web-platform-features to share your screen'); } const streamId: string = await this.getDesktopShareFromExtension(); this.logger.debug('Resolving userMedia from dekstopShare')(); stream = await navigator.mediaDevices.getUserMedia(<MediaStreamConstraints><unknown>{ // TODO update ts to support this audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: streamId, maxWidth: window.screen.width, maxHeight: window.screen.height } } }); } const tracks: any[] = stream.getVideoTracks(); if (!(tracks && tracks.length > 0)) { throw Error('No video tracks from captured screen'); } tracks[0].isShare = true; } return stream; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private combineStreams (...streams: (MediaStream|null)[]): MediaStream|null { let stream: MediaStream|null = null; streams.forEach(s => { if (s) { if (!stream) { stream = s; } else { for (let t of s.getTracks()) { stream.addTrack(t); } } } }); return stream; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private handleStream(e: string, endStream: MediaStream|null) { const what = []; if (this.callInfo.showMic) { what.push('audio'); } if (this.callInfo.showVideo) { what.push('video'); } if (this.callInfo.shareScreen) { what.push('screenshare'); } const message = `<span>Failed to capture ${what.join(', ')} source</span>, because ${extractError(e)}`; stopVideo(endStream); this.store.growlErrorRaw(message); this.logger.error('onFailedCaptureSource {}', e)(); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private attachLocalStream(stream: MediaStream|null) { this.logger.log('Local stream has been attached'); if (stream) { this.localStream = stream; this.audioProcessor = createMicrophoneLevelVoice(stream, this.processAudio.bind(this)); const payload: MediaIdentifier = { id: this.roomId, media: stream }; this.store.setLocalStreamSrc(payload); } this.setCallIconsState(); }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
MethodDeclaration
private setCallStatus(status: CallStatus) { this.logger.log('Setting call status to {}', status)(); this.callStatus = status; }
Master0229/pychat-master
frontend/src/ts/webrtc/call/CallHandler.ts
TypeScript
ArrowFunction
(csrfToken: string) => { return { "X-CSRF-Token": csrfToken }; }
pmaidminutes/hedi-app
modules/auth/server/oauth/utils/authHeader.ts
TypeScript
ArrowFunction
(accessToken: string) => { return { Authorization: "Bearer " + accessToken }; }
pmaidminutes/hedi-app
modules/auth/server/oauth/utils/authHeader.ts
TypeScript
ArrowFunction
( args: Pick<IAuth, "accessToken" | "csrfToken"> ) => { return { ...toBearerObject(args.accessToken), ...toCSRFObject(args.csrfToken), } as IAuthHeader; }
pmaidminutes/hedi-app
modules/auth/server/oauth/utils/authHeader.ts
TypeScript