Skip to content

Commit

Permalink
Merge pull request #19 from signalwire/aa/prettier
Browse files Browse the repository at this point in the history
Setup prettier
  • Loading branch information
iAmmar7 authored Jan 15, 2024
2 parents 2fb784c + f532796 commit 5e1d001
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 102 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ name: Docker

on:
push:
branches: [ main ]
branches: [main]
pull_request:
branches: [ main ]
branches: [main]

env:
TEST_TAG: call-fabric-client-beta
Expand Down
25 changes: 12 additions & 13 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,22 @@ name: Node.js CI

on:
push:
branches: [ "main" ]
branches: ['main']
pull_request:
branches: [ "main" ]
branches: ['main']

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: 20.x
cache: 'npm'
- run: npm ci
- run: npm audit
- run: npm run build --if-present
- run: npm test
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: 20.x
cache: 'npm'
- run: npm ci
- run: npm audit
- run: npm run build --if-present
- run: npm test
11 changes: 11 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"printWidth": 80,
"trailingComma": "es5",
"useTabs": false,
"tabWidth": 2,
"semi": false,
"singleQuote": true,
"jsxSingleQuote": true,
"jsxBracketSameLine": false,
"arrowParens": "always"
}
151 changes: 82 additions & 69 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
require('dotenv').config();
const express = require('express');
const session = require('express-session');
const app = express();
const base64url = require('base64url');
const crypto = require('crypto');

app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static('public'));
app.use(session({ secret: process.env.SESSION_SECRET, resave: true, saveUninitialized: true }));
require('dotenv').config()
const express = require('express')
const session = require('express-session')
const app = express()
const base64url = require('base64url')
const crypto = require('crypto')

app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(express.static('public'))
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
})
)

const FIREBASE_CONFIG = JSON.stringify({
apiKey: process.env.FIREBASE_API_KEY,
Expand All @@ -25,140 +31,147 @@ const FIREBASE_CONFIG = JSON.stringify({
const host = process.env.RELAY_HOST

async function apiRequest(uri, options) {
const response = await fetch(uri, options);
const response = await fetch(uri, options)

if (!response.ok) {
console.log('error response:', await response.text());
throw new Error(`HTTP error! status: ${response.status}`);
console.log('error response:', await response.text())
throw new Error(`HTTP error! status: ${response.status}`)
}

return await response.json();
return await response.json()
}

async function getAccessToken(code, verifier) {
const params = new URLSearchParams();
params.append('client_id', process.env.OAUTH_CLIENT_ID);
params.append('grant_type', 'authorization_code');
params.append('code', code);
params.append('redirect_uri', process.env.OAUTH_REDIRECT_URI);
params.append('code_verifier', verifier);
const params = new URLSearchParams()
params.append('client_id', process.env.OAUTH_CLIENT_ID)
params.append('grant_type', 'authorization_code')
params.append('code', code)
params.append('redirect_uri', process.env.OAUTH_REDIRECT_URI)
params.append('code_verifier', verifier)

return await apiRequest(process.env.OAUTH_TOKEN_URI, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: params
});
body: params,
})
}

async function getUserInfo(accessToken) {
return await apiRequest(process.env.OAUTH_USERINFO_URI, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
}
});
Authorization: `Bearer ${accessToken}`,
},
})
}

async function getSubscriberToken() {
const tokenRequest = {
reference: process.env.SUBSCRIBER_REFERENCE,
password: process.env.SUBSCRIBER_PASSWORD,
application_id: process.env.OAUTH_APPLICATION_ID
application_id: process.env.OAUTH_APPLICATION_ID,
}

return await apiRequest(`https://${process.env.SIGNALWIRE_SPACE}/api/fabric/subscribers/tokens`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${Buffer.from(`${process.env.SIGNALWIRE_PROJECT_KEY}:${process.env.SIGNALWIRE_TOKEN}`).toString('base64')}`
},
body: JSON.stringify(tokenRequest)
});
return await apiRequest(
`https://${process.env.SIGNALWIRE_SPACE}/api/fabric/subscribers/tokens`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Basic ${Buffer.from(
`${process.env.SIGNALWIRE_PROJECT_KEY}:${process.env.SIGNALWIRE_TOKEN}`
).toString('base64')}`,
},
body: JSON.stringify(tokenRequest),
}
)
}

app.get('/', async (req, res) => {
let token;
let token
if (req.session && req.session.token) {
token = req.session.token
} else {
const response = getSubscriberToken();
token = response.token;
const response = getSubscriberToken()
token = response.token
}

res.render('index', {
host,
token: token,
destination: process.env.DEFAULT_DESTINATION,
firebaseConfig: FIREBASE_CONFIG,
});
});
})
})

app.get('/minimal', async (req, res) => {
let token;
let token
if (req.session && req.session.token) {
token = session.token
}else {
const response = getSubscriberToken();
token = response.token;
} else {
const response = getSubscriberToken()
token = response.token
}

res.render('minimal', {
host,
token: token,
destination: process.env.DEFAULT_DESTINATION,
firebaseConfig: FIREBASE_CONFIG,
});
});
})
})

app.get('/oauth', (req, res) => {
console.log('oauth: begin initiation');
console.log('oauth: begin initiation')

const authEndpoint = process.env.OAUTH_AUTH_URI;
const verifier = base64url(crypto.pseudoRandomBytes(32));
req.session.verifier = verifier;
const challenge = base64url(crypto.createHash('sha256').update(verifier).digest());
const authEndpoint = process.env.OAUTH_AUTH_URI
const verifier = base64url(crypto.pseudoRandomBytes(32))
req.session.verifier = verifier
const challenge = base64url(
crypto.createHash('sha256').update(verifier).digest()
)

const queryParams = new URLSearchParams({
response_type: 'code',
client_id: process.env.OAUTH_CLIENT_ID,
redirect_uri: process.env.OAUTH_REDIRECT_URI,
code_challenge: challenge,
code_challenge_method: 'S256'
code_challenge_method: 'S256',
})

const authorizationUri = `${authEndpoint}?${queryParams}`

res.redirect(authorizationUri);
});
res.redirect(authorizationUri)
})

app.get('/callback', async (req, res) => {
console.log('oauth: process callback');
console.log('oauth: process callback')

try {
const tokenData = await getAccessToken(req.query.code, req.session.verifier);
const token = tokenData.access_token;
req.session.token = token;
const tokenData = await getAccessToken(req.query.code, req.session.verifier)
const token = tokenData.access_token
req.session.token = token

const userInfo = await getUserInfo(token);
req.session.user = userInfo;
const userInfo = await getUserInfo(token)
req.session.user = userInfo

res.redirect('/');
res.redirect('/')
} catch (error) {
console.error(error);
console.error(error)
}
});
})

app.get('/service-worker.js', async (req, res) => {
res.set({
'Content-Type': 'application/javascript; charset=UTF-8'
'Content-Type': 'application/javascript; charset=UTF-8',
})

res.render('service-worker', {
firebaseConfig: FIREBASE_CONFIG,
});
});
})
})

app.listen(process.env.PORT || 3000, () => {
console.log("Server running on port 3000");
});
console.log('Server running on port 3000')
})
15 changes: 8 additions & 7 deletions public/full.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const {
supportsMediaOutput,
createDeviceWatcher,
createMicrophoneAnalyzer,
} = SignalWire;
} = SignalWire

window.getMicrophoneDevices = getMicrophoneDevices
window.getCameraDevices = getCameraDevices
Expand All @@ -24,7 +24,7 @@ window.getSpeakerDevicesWithPermissions = getSpeakerDevicesWithPermissions
let roomObj = null
let client = null
let micAnalyzer = null
let pnSecretKey = null;
let pnSecretKey = null

const inCallElements = [
roomControls,
Expand Down Expand Up @@ -102,9 +102,10 @@ async function enablePushNotifications() {

console.log(
'Service Worker registration successful with registration: ',
registration,
registration
)
const serviceWorker = registration.active ?? registration.waiting ?? registration.installing
const serviceWorker =
registration.active ?? registration.waiting ?? registration.installing
if (serviceWorker.state !== 'activated') {
await new Promise((resolve) => {
serviceWorker.addEventListener('statechange', ({ target }) => {
Expand Down Expand Up @@ -170,7 +171,7 @@ async function handlePushNotification(pushNotificationPayload) {
}

function b642ab(base64_string) {
return Uint8Array.from(window.atob(base64_string), c => c.charCodeAt(0));
return Uint8Array.from(window.atob(base64_string), (c) => c.charCodeAt(0))
}

async function readPushNotification(payload) {
Expand Down Expand Up @@ -852,9 +853,9 @@ window.ready(async function () {
console.log('Ready!')
const client = await getClient()
await client.connect()
const searchParams = new URLSearchParams(location.search);
const searchParams = new URLSearchParams(location.search)
console.log('Handle inbound?', searchParams.has('inbound'))
if (searchParams.has('inbound')) {
await enablePushNotifications()
}
})
})
Loading

0 comments on commit 5e1d001

Please sign in to comment.