const gql = require('graphql-tag'); const crypto = require('crypto'); const fetch = require('node-fetch'); const environment = 'demo.ownzones.com'; // this is the API endpoint where the GraphQL interface is exposed const endpoint = 'graphql-gateway.external.demo.oz.nico.ownzones.com/graphql'; /** * generating the api keys: * - in Connect console go to your username (top right corner) > "Edit Account" * - click New Api Key * - click SAVE and copy your keys in the variables below * note: this is the first and the LAST time when you'll see your secret key; if somehow you will lose it, you need to generate another pair of keys */ const orgSlug = 'ownzones-demo'; const publicKey = ''; const secretKey = ''; /** * A helper function to create a file locator structure from a file path. */ function makeS3Locator(bucket, path) { return { type: 'S3FileLocator', bucket, key: path, url: `s3://${bucket}/${path}`, }; } /** * Generic method to send a GraphQL request to the Connect API. */ async function request(query, variables) { // generate the request signature const body = JSON.stringify([{ query, variables }]); const payload = { url: endpoint, body, organization_slug: orgSlug, }; const hmac = crypto.createHmac('sha256', secretKey); hmac.write(JSON.stringify(payload)); hmac.end(); const signature = hmac.read().toString('hex'); // send the request, including the signature const response = await fetch(`https://${endpoint}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Organization-Slug': orgSlug, 'oz-key-id': publicKey, 'oz-signature': signature }, body: JSON.stringify([{ query, variables, }]), }); if (response.status !== 200) { const body = await response.text(); throw new Error(body); } else { const body = await response.json(); const gqlResponse = body[0]; if (gqlResponse.errors) { throw new Error(gqlResponse.errors[0].message); } return gqlResponse.data; } }; /** * Obtains the ID of a file by performing a search in the Connect inventory. */ async function findMediaItem(filename) { const query = gql` query FindMediaItemByFilename($filename: String!) { files(search: $filename) { edges { node { id assetId filename ingestWorkflow { id status } } } } } `; const data = await request(query, { filename }); if (data.files.edges.length === 0) { throw new Error('File not found'); } return data.files.edges[0].node; } /** * Obtains information about a background Connect workflow. */ async function checkWorkflow(id) { const query = gql` query CheckWorkflow($id: ID!) { workflow(id: $id) { id status progress tasks { id type status error { message } } } } `; const response = await request(query, { id }); return response.workflow; } module.exports = { environment, endpoint, orgSlug, makeS3Locator, request, findMediaItem, checkWorkflow, };