npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

destream-api

v1.1.1

Published

Full featured DeStream API NodeJS wrapper [BETA]

Downloads

4

Readme

DeStream-API — Full featured DeStream API NodeJS wrapper [BETA]

destream-api currently supports:

  • authentification (getting access tokens, refreshing them)
  • user info retreiving
  • registering user with email
  • getting latest donations with pagination support (.next(), .prev() functions on result), limit, offset, date-filtering
  • creating invoices (filled donation forms) and getting information about latest invoices
  • subscribing to events on websocket server such as new donations

Code with/without using destream-api library

Refresh Access Token with hardcoded refresh token

/* Without using destream-api */

const fetch = require('node-fetch')
const formurlencoded = require('form-urlencoded')

let params = formurlencoded({
  grant_type: 'refresh_token',
  client_id: 12345,
  client_secret: 'secret-secret',
  scope: 'profile+tips',
  refresh_token: 'refresh_token'
})

fetch(`https://destream.net/api/v2/oauth2/token?${params}`, {
  method: 'POST',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
/* Using destream-api */

const DeStreamAPI = require('destream-api')
let destream = new DeStreamAPI({clientId: '12345', clientSecret: 'secret-secret'})
destream.refreshAccessToken('profile+tips', 'refresh_token' })

Getting an array of all tips

/* Without using destream-api */

const fetch = require('node-fetch')

const limit = 10; let tipsArray = [], offset = 0;
while(true){
  fetch(`https://destream.net/api/v2/users/tips?offset=${offset}`, {
    method: 'GET',
    headers: {
      'X-Api-ClientId': '12345',
      'Authorization': `access_token jahs62d123`
    }
  }).then(result => result.json()).then(result => {
    if(result.data.length === 0){
      break;
    } else {
      tipsArray.push(...result.data)
    }
    offset += limit
  })
}
/* Using destream-api */

const DeStreamAPI = require('destream-api')

let destream = new DeStreamAPI({clientId: '12345', clientSecret: 'secret-secret'})

let tipsArray = []
let tips = await destream.getTips({ tokenType: 'access_token', access_token: 'jahs62d123' })
while(tips.next){
  let tips = await tips.next()
  tipsArray.push(...tips.data)
}

More examples

Installation

$ npm i destream-api

or with yarn

$ yarn add destream-api

Usage

Each method except for subscribeToEvents() and validateSignature() has http_status property in returned object; object is parsed JSON response.

const DeStreamAPI = require('destream-api')

let destream = new DeStreamAPI({clientId: '12345', clientSecret: 'secret-secret-secret'})

async function registerMe() {
  let response = await destream.registerUser('[email protected]')
  console.log(response)
} registerMe()

API Reference

DeStream API Documentation (ru)

Token & authentification

async getTokensFromCode(authorizationCode, redirectUri)

Exchanges authorization code from oauth to access token, refresh token, token type.

Example usage:

let { access_token, refresh_token, token_type, http_status } = await destream.getTokensFromCode('lk12j3a1p', 'https://destream.ru/')

async refreshAccessToken(scope, refresh_token)

Refreshes access token so it won't expire. Be aware that you have to use value from scope field in response with your tokens. So don't use + as delimiter of scopes, use , instead.

Example usage:

let { access_token, refresh_token, token_type, http_status } = await destream.refreshAccessToken('profile,tips', '2QwlfWHU7OYs')

Users

async getUser(token_type, access_token)

Gets user which gave your app access to its account. If Access Token expired or incorrect, will throw DeStreamAPI.AccessTokenIncorrect exception for 401 http status with API response included in apiResponse property in it.

Example usage:

let { data } = await destream.getUser('Bearer', '3jjprwOCd1Gi')
console.log(data.nickname, data.email)

async registerUser(email)

Register new user on destream with specified email. If user exists, throws an DeStreamAPI.UserExistsException exception with API response included in it in apiResponse property.

Example usage:

let { newUser, http_status } = await destream.registerUser('[email protected]')
console.log('User created!', newUser.data.user_id)

Tips + polling & websocket server

async getTips(tokens, offset, limit, sinceDate)

Gets latest tips. Tokens is an object: { token_type: 'string', access_token: 'string' }; Everything else is optional: offset and limit are Numbers; sinceDate is Date object

If Access Token expired or incorrect, will throw DeStreamAPI.AccessTokenIncorrect exception for 401 http status with API response included in apiResponse property in it.

Example usage:

let { data, total } = await destream.getTips({ token_type: 'Bearer', access_token: '3jjprwOCd1Gi'})
console.log('You have', total, 'tips with total amount sum of', data.reduce((prev, cur) => prev+cur.amount, 0), '!')

subscribeToEvents(access_token, callback)

Subscribes you to websocket server which sends you messages such as donationReceived. Callback function is called every time with exactly 1 argument: message text.

Example usage:

destream.subscribeToEvents('lk12j3a1p', message => {
  console.log('WOO HOOO! DONATE!!!', message.sender, 'I LOVE YOU SO MUCH thanks for', message.amount, message.currency)
})

Invoices (kinda)

I call it invoices because it is literally invoice: user is redirected directly to pay page. No forms needed to be filled by user.

User can change any parameters in payment URL (such as amount, currency, message), so be sure to always compare received amount with requested!

async createInvoice(user_id, amount, currency, optionalData)

Creates an invoice with specified parameters. All arguments but optionalData are required;

Optional data is an object in which every property is optional. If you choose to add any property, it will be passed to the DeStream API endpoint.

{
  message: string;
  success_url: string;
  fail_url: string;
  additional_data: string;
}

Example usage:

let invoice = await destream.createInvoice('eb4abb4a75ea408bb5af8f9f98a406cc', 100, 'RUB')
console.log('Invoice with', invoice.data.payment_id, 'created. Now please go to', invoice.data.payment_url)

async getInvoicesPayments(tokens, offset, limit, sinceDate, arrayOfIds)

Gets information about created invoices. Tokens is an object: { token_type: 'string', access_token: 'string' }; Everything else is optional: offset and limit are Numbers; sinceDate is Date object; arrayOfIds must be an array of numbers (payment_ids)

If Access Token expired or incorrect, will throw DeStreamAPI.AccessTokenIncorrect exception for 401 http status with API response included in apiResponse property in it.

Example usage:

let tenCreatedInvoices = await destream.getInvoicesPayments({ token_type: 'Bearer', access_token: '3jjprwOCd1Gi'})
console.log('You created these invoices: ', ...tenCreatedInvoices.data.map(invoice => invoice.payment_id))

Notifications on webhook

You have to setup server by yourself, but this library provides useful methods for webhook.

validateSignature(body, receivedSignature)

Concatenates body with clientSecret and hashes to SHA512. Returns true if equal to receivedSignature, false otherwise.

Example usage:

if(!destream.validateSignature(req.body, req.headers['X-Signature'])){
  throw 'Signature invalid!!'
}