1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
/**
* A class for authenticating and talking to the mediumroast.io backend
* @author Michael Hay <michael.hay@mediumroast.io>
* @file gitHubServer.js
* @copyright 2024 Mediumroast, Inc. All rights reserved.
* @license Apache-2.0
* @version 2.0.0
*
* @class baseObjects
* @classdesc An implementation for interacting with the GitHub backend.
*
* @requires GitHubFunctions
* @requires crypto
* @requires fs
* @requires path
* @requires fileURLToPath
*
* @exports {Studies, Companies, Interactions, Users, Storage, Actions}
*
* @example
* import {Companies, Interactions, Users, Billings} from './api/gitHubServer.js'
* const companies = new Companies(token, org, processName)
* const interactions = new Interactions(token, org, processName)
* const users = new Users(token, org, processName)
* const billings = new Billings(token, org, processName)
*
* const allCompanies = await companies.getAll()
* const allInteractions = await interactions.getAll()
* const allUsers = await users.getAll()
* const allBillings = await billings.getAll()
*
* const company = await companies.findByName('myCompany')
* const interaction = await interactions.findByName('myInteraction')
* const user = await users.findByName('myUser')
*
*/
// Import required modules
import GitHubFunctions from './github.js'
import { createHash } from 'crypto'
import fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
class baseObjects {
constructor(token, org, processName, objType) {
this.serverCtl = new GitHubFunctions(token, org, processName)
this.objType = objType
this.objectFiles = {
Studies: 'Studies.json',
Companies: 'Companies.json',
Interactions: 'Interactions.json',
Users: null
}
}
/**
* @async
* @function getAll
* @description Get all objects from the mediumroast.io application
* @returns {Array} the results from the called function mrRest class
*/
async getAll() {
return await this.serverCtl.readObjects(this.objType)
}
/**
* @async
* @function findByName
* @description Find all objects by name from the mediumroast.io application
* @param {String} name - the name of the object to find
* @returns {Array} the results from the called function mrRest class
*/
async findByName(name) {
return this.findByX('name', name)
}
/**
* @async
* @function findById
* @description Find all objects by id from the mediumroast.io application
* @param {String} id - the id of the object to find
* @param {String} endpoint - defaults to findbyx and is combined with credential and version info
* @returns {Array} the results from the called function mrRest class
* @deprecated
*/
async findById(id) {
return false
const fullEndpoint = '/' + this.apiVersion + '/' + this.objType + '/' + endpoint
const my_obj = {findByX: "id", xEquals: id}
return this.rest.postObj(fullEndpoint, my_obj)
}
/**
* @async
* @function findByX
* @description Find all objects by attribute and value pair from the mediumroast.io application
* @param {String} attribute - the attribute used to find objects
* @param {String} value - the value for the defined attribute
* @returns {Array} the results from the called function mrRest class
*/
async findByX(attribute, value, allObjects=null) {
if(attribute === 'name') {
value = value.toLowerCase()
}
// console.log(`Searching for ${this.objType} where ${attribute} = ${value}`)
let myObjects = []
if(allObjects === null) {
const allObjectsResp = await this.serverCtl.readObjects(this.objType)
allObjects = allObjectsResp[2].mrJson
}
// If the length of allObjects is 0 then return an error
// This will occur when there are no objects of the type in the backend
if(allObjects.length === 0) {
return [false, {status_code: 404, status_msg: `no ${this.objType} found`}, null]
}
for(const obj in allObjects) {
let currentObject
attribute == 'name' ? currentObject = allObjects[obj][attribute].toLowerCase() : currentObject = allObjects[obj][attribute]
if(currentObject === value) {
myObjects.push(allObjects[obj])
}
}
if (myObjects.length === 0) {
return [false, {status_code: 404, status_msg: `no ${this.objType} found where ${attribute} = ${value}`}, null]
} else {
return [true, `SUCCESS: found all objects where ${attribute} = ${value}`, myObjects]
}
}
/**
* @async
* @function createObj
* @description Create objects in the mediumroast.io application
* @param {Array} objs - the objects to create in the backend
* @returns {Array} the results from the called function mrRest class
*/
// async createObj1(objs) {
// return await this.serverCtl.createObjects(this.objType, objs)
// }
async createObj(objs) {
// Create the repoMetadata object
let repoMetadata = {
containers: {
[this.objType]: {}
},
branch: {}
}
// Catch the container
const caught = await this.serverCtl.catchContainer(repoMetadata)
// If the container is locked then return the caught object
if(!caught[0]) {
return caught
}
// Get the sha for the current branch/object
const sha = await this.serverCtl.getSha(
this.objType,
this.objectFiles[this.objType],
repoMetadata.branch.name
)
// If the sha is not found then return the sha object
if(!sha[0]) {
return sha
}
// Append the new object to the existing objects
const mergedObjects = [...caught[2].containers[this.objType].objects, ...objs]
// Write the new objects to the container
const writeResp = await this.serverCtl.writeObject(
this.objType,
mergedObjects,
repoMetadata.branch.name,
sha[2]
)
// If the write fails then return the writeResp
if(!writeResp[0]) {
return writeResp
}
// Release the container
const released = await this.serverCtl.releaseContainer(caught[2])
// If the release fails then return the released object
if(!released[0]) {
return released
}
// Return a success message
return [true, {status_code: 200, status_msg: `created [${objs.length}] ${this.objType}`}, null]
}
/**
* @async
* @function updateObj
* @description Update an object in the mediumroast.io application
* @param {Object} obj - the object to update in the backend which includes the id and, the attribute and value to be updated
* @param {String} endpoint - defaults to findbyx and is combined with credential and version info
* @returns {Array} the results from the called function mrRest class
*/
async updateObj(objName, key, value, dontWrite, system, whiteList) {
return await this.serverCtl.updateObject(this.objType, objName, key, value, dontWrite, system, whiteList)
}
/**
* @async
* @function deleteObj
* @description Delete an object in the mediumroast.io application
* @param {String} id - the object to be deleted in the mediumroast.io application
* @param {String} endpoint - defaults to findbyx and is combined with credential and version info
* @returns {Array} the results from the called function mrRest class
* @todo implment when available in the backend
*/
async deleteObj(objName, source, repoMetadata=null, catchIt=true) {
return await this.serverCtl.deleteObject(objName, source, repoMetadata, catchIt)
}
/**
* @async
* @function linkObj
* @description Link objects in the mediumroast.io application
* @param {Array} objs - the objects to link in the backend
* @returns {Array} the results from the called function mrRest class
*/
linkObj(objs) {
let linkedObjs = {}
for(const obj in objs) {
const objName = objs[obj].name
const sha256Hash = createHash('sha256').update(objName).digest('hex')
linkedObjs[objName] = sha256Hash
}
return linkedObjs
}
// Create a function that checks for a locked container using the serverCtl.checkForLock() function
async checkForLock() {
return await this.serverCtl.checkForLock(this.objType)
}
}
class Studies extends baseObjects {
/**
* @constructor
* @classdesc A subclass of baseObjects that construct the study objects
* @param {String} token - the token for the GitHub application
* @param {String} org - the organization for the GitHub application
* @param {String} processName - the process name for the GitHub application
*/
constructor (token, org, processName) {
super(token, org, processName, 'Studies')
}
}
// Create a subclass called Users that inherits from baseObjects
class Users extends baseObjects {
/**
* @constructor
* @classdesc A subclass of baseObjects that construct the user objects
* @param {String} token - the token for the GitHub application
* @param {String} org - the organization for the GitHub application
* @param {String} processName - the process name for the GitHub application
*/
constructor (token, org, processName) {
super(token, org, processName, 'Users')
}
// Create a new method for getAll that is specific to the Users class using getUser() in github.js
async getAll() {
return await this.serverCtl.getAllUsers()
}
// Create a new method for findMyself that is specific to the Users class using getUser() in github.js
async getMyself() {
return await this.serverCtl.getUser()
}
async findByName(name) {
return this.findByX('login', name)
}
async findByX(attribute, value) {
let myUsers = []
const allUsersResp = await this.getAll()
const allUsers = allUsersResp[2]
for(const user in allUsers) {
if(allUsers[user][attribute] === value) {
myUsers.push(allUsers[user])
}
}
return [true, `SUCCESS: found all users where ${attribute} = ${value}`, myUsers]
}
}
// Create a subclass called Users that inherits from baseObjects
class Storage extends baseObjects {
/**
* @constructor
* @classdesc A subclass of baseObjects that construct the user objects
* @param {String} token - the token for the GitHub application
* @param {String} org - the organization for the GitHub application
* @param {String} processName - the process name for the GitHub application
*/
constructor (token, org, processName) {
super(token, org, processName, 'Billings')
}
// Create a new method for getAll that is specific to the Billings class using getBillings() in github.js
async getAll() {
return await this.serverCtl.getRepoSize()
}
// Create a new method of to get the storage billing status only
async getStorageBilling() {
return await this.serverCtl.getStorageBillings()
}
}
class Companies extends baseObjects {
/**
* @constructor
* @classdesc A subclass of baseObjects that construct the company objects
* @param {String} token - the token for the GitHub application
* @param {String} org - the organization for the GitHub application
* @param {String} processName - the process name for the GitHub application
*/
constructor (token, org, processName) {
super(token, org, processName, 'Companies')
}
async updateObj(objToUpdate, dontWrite=false, system=false) {
// Destructure objToUpdate
const { name, key, value } = objToUpdate
// Define the attributes that can be updated by the user
const whiteList = [
'description', 'company_type', 'url', 'role', 'wikipedia_url', 'status', 'logo_url',
'region', 'country', 'city', 'state_province', 'zip_postal', 'street_address', 'latitude', 'longitude','phone',
'google_maps_url', 'google_news_url', 'google_finance_url','google_patents_url',
'cik', 'stock_symbol', 'stock_exchange', 'recent_10k_url', 'recent_10q_url', 'firmographic_url', 'filings_url', 'owner_tranasactions',
'industry', 'industry_code', 'industry_group_code', 'industry_group_description', 'major_group_code','major_group_description'
]
return await super.updateObj(name, key, value, dontWrite, system, whiteList)
}
async deleteObj(objName, allowOrphans=false) {
let source = {
from: 'Companies',
to: ['Interactions']
}
// If allowOrphans is true then use the baseObjects deleteObj
if(allowOrphans){
return await super.deleteObj(objName, source)
}
// Catch the Companies and Interaction containers
// Assign repoMetadata to capture Companies nad Studies
let repoMetadata = {
containers: {
Companies: {},
Interactions: {}
},
branch: {}
}
const caught = await this.serverCtl.catchContainer(repoMetadata)
// Use findByX to get all linkedInteractions
// NOTE: This has to be done here because the company has been deleted in the next step
const getCompanyObject = await this.findByX('name', objName, caught[2].containers.Companies.objects)
if(!getCompanyObject[0]) {
return getCompanyObject
}
const linkedInteractions = getCompanyObject[2][0].linked_interactions
// Delete the company
// Use deleteObj to delete the company
const deleteCompanyObjResp = await this.serverCtl.deleteObject(
objName,
source,
caught[2],
false
)
if(!deleteCompanyObjResp[0]) {
return deleteCompanyObjResp
}
// Delete all linkedInteractions
// Update source to be from the perspective of the Interactions
source = {
from: 'Interactions',
to: ['Companies']
}
// Use deleteObect to delete all linkedInteractions
for(const interaction in linkedInteractions) {
const deleteInteractionObjResp = await this.serverCtl.deleteObject(
interaction,
source,
caught[2],
false
)
if(!deleteInteractionObjResp[0]) {
return deleteInteractionObjResp
}
}
// Release the container
const relased = await this.serverCtl.releaseContainer(caught[2])
if(!relased[0]) {
return relased
}
// Return the response
return [true, {status_code: 200, status_msg: `deleted company [${objName}] and all linked interactions`}, null]
}
}
class Interactions extends baseObjects {
/**
* @constructor
* @classdesc A subclass of baseObjects that construct the interaction objects
* @param {String} token - the token for the GitHub application
* @param {String} org - the organization for the GitHub application
* @param {String} processName - the process name for the GitHub application
*/
constructor (token, org, processName) {
super(token, org, processName, 'Interactions')
}
async updateObj(objToUpdate, dontWrite=false, system=false) {
// Destructure objToUpdate
const { name, key, value } = objToUpdate
// Define the attributes that can be updated by the user
const whiteList = [
'status', 'content_type', 'file_size', 'reading_time', 'word_count', 'page_count', 'description', 'abstract',
'region', 'country', 'city', 'state_province', 'zip_postal', 'street_address', 'latitude', 'longitude',
'public', 'groups'
]
return await super.updateObj(name, key, value, dontWrite, system, whiteList)
}
async deleteObj(objName) {
const source = {
from: 'Interactions',
to: ['Companies']
}
return await super.deleteObj(objName, source)
}
async findByHash(hash) {
return this.findByX('file_hash', hash)
}
}
class Actions extends baseObjects {
/**
* @constructor
* @classdesc A subclass of baseObjects that construct the interaction objects
* @param {String} token - the token for the GitHub application
* @param {String} org - the organization for the GitHub application
* @param {String} processName - the process name for the GitHub application
*/
constructor (token, org, processName) {
super(token, org, processName, 'Actions')
}
_generateManifest(dir, filelist) {
// Define which content to skip
const skipContent = ['.DS_Store', 'node_modules']
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename);
// Use regex to prune everything after mediumroast_js/
const basePath = __dirname.match(/.*mediumroast_js\//)[0];
// Append cli/actions to the base path
dir = dir || path.resolve(path.join(basePath, 'cli/actions'))
const files = fs.readdirSync(dir)
filelist = filelist || [];
files.forEach((file) => {
// Skip unneeded directories
if (skipContent.includes(file)) {
return
}
const fullPath = path.join(dir, file);
if (fs.statSync(fullPath).isDirectory()) {
filelist = this._generateManifest(path.join(dir, file), filelist)
} else {
// Substitute .github for the first part of the path, in the variable dir
if (dir.includes('./')) {
dir = dir.replace('./', '')
}
// This will be the repository name
let dotGitHub = dir.replace(/.*(workflows|actions)/, '.github/$1')
filelist.push({
fileName: file,
containerName: dotGitHub,
srcURL: new URL(`file://${fullPath}`)
})
}
})
return filelist
}
async updateActions() {
// Discover the manifest
const actionsManifest = this._generateManifest()
// Capture detailed install status
let installStatus = {
successCount: 0,
failCount: 0,
success: [],
fail: [],
total: actionsManifest.length
}
for (const action of actionsManifest) {
// Loop through the actionsManifest and install each action
let status = false
let blobData
try {
// Read in the blob file
blobData = fs.readFileSync(action.srcURL, 'base64')
status = true
} catch (err) {
// console.log(`Unable to read file [${action.fileName}] because: ${err}`)
return [false,{status_code: 500, status_msg: `Unable to read file [${action.fileName}] because: ${err}`}, installStatus]
}
if(status) {
// Get the sha for the current branch/object
const sha = await this.serverCtl.getSha(
action.containerName,
action.fileName,
'main'
)
// Keep action update failures
// Install the action
const installResp = await this.serverCtl.writeBlob(
action.containerName,
action.fileName,
blobData,
'main',
sha[2]
)
if(installResp[0]){
installStatus.success.push({fileName: action.fileName, containerName: action.catchContainer, installMsg: installResp[1].status_msg})
installStatus.successCount++
} else {
installStatus.fail.push({fileName: action.fileName, containerName: action.catchContainer, installMsg: installResp[1].status_msg})
installStatus.failCount++
}
} else {
return [false, {status_code: 503,status_msg:`Failed to read item [${action.fileName}]`}, installStatus]
}
}
return [true, {status_code: 200, status_msg:`All actions installed`}, installStatus]
}
// Create a new method of to get the actions billing status only
async getActionsBilling() {
return await this.serverCtl.getActionsBillings()
}
async getAll() {
return await this.serverCtl.getWorkflowRuns()
}
}
// Export classes for consumers
export { Studies, Companies, Interactions, Users, Storage, Actions }