Skip to content

K1GOL/rtcbeam-core

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

23 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

rtcbeam-core

Peer-to-peer end-to-end encrypted file and data transfer module using PeerJS. Provides core functionality for rtcbeam. Can be used to send any kind of data between two peers. Designed for, but not limited to, file transfer.


Usage

IMPORTANT NOTE

rtcbeam-core is built with PeerJS, a peer-to-peer library that (unfortunately) will not function outside of a browser. As a result, rtcbeam-core will only work if run in a browser.

Installation

npm i rtcbeam-core

import { Rtcbeam } from 'rtcbeam-core'

Rtcbeam([host, options])

Create a new instance of the Rtcbeam class with const rtcbeam = new Rtcbeam(host)

Parameters:

host (optional)
URL for any PeerServer used to broker connections. Default is 0.peerjs.com
options (optional)
Options that will be passed on to the PeerJS Peer constructor. Host will be overridden with the 'host' parameter.
const rtcbeam = new Rtcbeam('0.peerjs.com', { pingInterval: 10000 })

rtcbeam.getVersion()

Returns version number.

console.log(rtcbeam.getVersion())
// 1.2.3

rtcbeam.createPeer([host])

Creates new PeerJS peer. Can be called on an existing rtcbeam instance to reconnect to another connection broker server.

Parameters:

host (optional)
URL for any PeerServer used to broker connections. Default is 0.peerjs.com

Returns:

PeerJS peer object.

const rtcbeam = new Rtcbeam('0.peerjs.com')
console.log(rtcbeam.peer.options.host)
// 0.peerjs.com

rtcbeam.createPeer('server.example.com')
console.log(rtcbeam.peer.options.host)
// server.example.com

const newPeer = rtcbeam.createPeer('server.example.com')
console.log(newPeer.options.host)
// server.example.com

rtcbeam.serveData(blob[, name, isFile])

Serve new data from your rtcbeam client that can be requested by other clients. Maximum size for single blob is about 800 megabytes.

Parameters:

blob
Any Javascript Blob containing the data that will be served.
name (optional)
Name of the data. If no name is provided, the MIME type of the blob will be used.
isFile (optional)
Boolean that should be true if the served data should be interpreted as a file, false otherwise. Default is true.

Returns:

Content ID of the served data. CID will be used by other peers to request this data.

const cid = rtcbeam.serveData(new Blob(['Hello world!']), 'hello', false)

/* -- or -- */

const cid = rtcbeam.serveData(new Blob(['data-read-from-file']), 'file.txt', true)

console.log(cid)
// CID of served data, for example
// 9907f5ca-ee52-44ac-abc1-74e31ceb6a95

rtcbeam.removeData(cid)

Removes served data and makes it no longer available.

Parameters:

cid
Content ID of the data to be removed.
const cid = rtcbeam.serveData(new Blob(['Hello world!']))
// Served.

rtcbeam.removeData(cid)
// Gone, reduced to atoms.

rtcbeam.requestData(id, cid[, encrypt])

Requests data from another client by client's ID and data CID.

Parameters:

id
ID of other peer.
cid
Content ID of the desired data from other peer.
encrypt (optional)
True for end-to-end encryption, false to skip encryption. Default is true.
rtcbeam.requestData('other-peer-id', 'some-cid')

rtcbeam.on('transfer-completed', (blob) => {
  blob.text().then(t => console.log(t))
  // Writes requested data as text.
})

rtcbeam.createStatusMessageSet(name[, values])

Creates a new status message set with user defined status messages. These messages will be passed on to the status event.

Parameters:

name
Name of the status message set. Cannot be "default". If one already exists with the same name, it will be overridden.
values (optional)
Object containing the new status messages, see below. If a value is missing, default will be used.

Available status messages and their default values:

networkConnecting: πŸ“‘ Establishing connection...

networkConnected: βœ… Connected to network.

error: ❌ An error has occured.

peerConnecting: πŸ’» Connecting to peer...

requestingData: ❔ Requesting file...

encryptingData: πŸ” Encrypting file...

sendingData: πŸ“‘ Sending file...

decryptingData: πŸ” Decrypting file...

transferCompleted: βœ… File transfer completed.

receivingData: πŸ“¨ Receiving file...

dataNotAvailable: ❌ File is no longer available.

// Default behaviour:
rtcbeam.on('status', status => {
  console.log(status)
  // When connected to network: βœ… Connected to network.
  // When sending data: πŸ“‘ Sending file...
  // etc...
})

/* --- */

// With custom status messages:
// Create a new set
rtcbeam.createStatusMessageSet('newMessageSet', {
  networkConnected: 'Hello world!',
  sendingData: 'Hello world, again!'
  // Other messages that are not specified will use default values.
})
// Use the new set.
rtcbeam.statusMessageSet = 'newMessageSet'

rtcbeam.on('status', status => {
  console.log(status)
  // When connected to network: Hello world!
  // When sending data: Hello world, again!
})

// To use default messages again:
rtcbeam.statusMessageSet = 'default'

Events:

Listen to with rtcbeam.on('event', (param1, param2...) => { ... })

.on('ready', () => { })

Emitted when rtcbeam client is ready and has connected to the provided PeerServer after initialization. Client can now be used for data transfer.

.on('status', (status) => { })

Emitted when the app status changes.

Parameters:

status
String describing the new app status.

.on('connection', (conn) => { })

Emitted when a new connection to this client has been established.

Parameters:

conn
Incoming PeerJS connection.

.on('send-start', () => { })

Emitted when client has started sending data.

.on('send-finish', () => { })

Emitted when client has finished sending data.

.on('send-progress', (progress, cid) => { })

Emitted repeatedly while sending data.

Parameters:

progress
Amount of bytes queued to be sent.
cid
Content ID of the data being sent that this progress update belongs to.

.on('receive-start', () => { })

Emitted when client has started recieving data.

.on('receive-progress', (progress, cid) => { })

Emitted repeatedly while sending data.

Parameters:

progress
Amount of bytes queued to be sent by peer sending data.
cid
Content ID of the data being received that this progress update belongs to.

.on('transfer-completed', (blob, metadata) => { })

Emitted when client has finished recieving data.

Parameters:

blob
Blob that was received from other client
metadata
Metadata about transferred data. Has the following values:

name
Name of the data.

type
MIME type of the data

cid
Content ID of the data.

isFile
True if the data should be interpreted as a file, false otherwise.

.on('not-found', (cid) => { })

Emitted when data has been requested from another peer but was not found by other peer.

Parameters:

cid
Content ID of the requested data.

Values:

Various values accessible within an instance of the Rtcbeam class.

.appStatus

String describing the current state of the app.

.peer

PeerJS peer used by the client.

.inboundData

Contains data being transferred to this client from others. Data structure:

.inboundData
β”‚
β”œ .cid-of-some-data
β”‚  β”œ .body      < blob containing data
β”‚  β”œ .name      < data name
β”‚  β”œ .type      < data MIME type
β”‚  β”œ .nonce     < encryption nonce
β”‚  β”” .secretKey < encryption secret key
β”‚
β”œ .cid-of-some-other-data
...

.outboundData

Contains data being served by this client and that can be transferred from this client to others. Data structure:

.outboundData
β”‚
β”œ .cid-of-some-data
β”‚  β”œ .body      < blob containing data
β”‚  β”œ .name      < data name
β”‚  β”œ .type      < data MIME type
β”‚  β”œ .nonce     < encryption nonce
β”‚  β”” .secretKey < encryption secret key
β”‚
β”œ .cid-of-some-other-data
...

.version

rtcbeam-core version. Identical to .getVersion()

.statusMessageSet

The name of the status message set that is being used. See .createStatusMessageSet(). Value for default set is default.

.statusMessages

This object stores different status message sets. Can be written to directly to change status messages, or to create a new message set. See .createStatusMessageSet(). Data structure:

.statusMessages
β”‚
β”œ .name-of-message-set
β”‚  β”œ .networkConnecting: string
β”‚  β”œ .networkConnected: string
β”‚  β”œ .error: string
β”‚  ...
β”‚  β”” .dataNotAvailable: string
β”‚
β”œ .name-of-some-other-message-set
...

Internal functions that are publicly accessible but are mostly useless:

deliverData (request, conn)

Delivers data to another client.

Parameters:

request
Request sent by another peer.
conn
PeerJS connection from other peer.
rtcbeam.on('connection', (conn) => {
  conn.on('data', (data) => {
    const request = JSON.parse(data)
    if (data.action === 'request-data') {
      rtcbeam.deliverData(request, conn)
    }
  })
})

receiveData(data, conn)

receives data from other peer. Data is written to rtcbeam.inboundData[cid], where cid is Content ID of transferred data. Parameters and usage are identical to deliverData()

handleIncomingData(data, conn)

Handles incoming requests and responds accordingly. Parameters are identical to deliverData()

confirmTransferFinish()

Called when data has been sent to other client.

notifyTransferStart()

Called when data is being received from other client.

dataNotFound(cid)

Called when data was requested but not found by other client.

Parameters:

cid
Content ID of requested data.

Example

// As noted above, bundle with Webpack, etc. and run in a browser.

import { Rtcbeam } from 'rtcbeam-core'

// Create a new client.
const firstClient = new Rtcbeam()

// Wait for client to be ready.
firstClient.on('ready', () => {
  // Create some data.
  const data = new Blob(['Hello world!'])

  // Serve that data and save cid.
  const cid = firstClient.serveData(data)

  // Create a second client to receive that data.
  const secondClient = new Rtcbeam()
  secondClient.on('ready', () => {
    // Handle incoming data.
    secondClient.on('transfer-completed', (blob, metadata) => {
      blob.text().then(t => {
        console.log(t)
        // Hello world!
      })
    })
    // Request served data.
    secondClient.requestData(firstClient.peer.id, cid)
  })
})

License

BSD 2-clause license.

About

Core module for rtcbeam

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published