servers.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { createHash, Color } from "./deps.ts";
  2. import type { server } from './deps.ts'
  3. export class Servers {
  4. servers: server[]
  5. iterator!: IterableIterator<server>
  6. current_server!: server
  7. constructor() {
  8. this.servers = []
  9. }
  10. async init(): Promise<server[]> {
  11. // store your BBB servers in servers.json
  12. const file: string = await Deno.readTextFile('servers.json')
  13. this.servers = JSON.parse(file)
  14. // create an iterator so that we can treat all servers equally
  15. this.iterator = this.servers[Symbol.iterator]();
  16. this.check()
  17. this.get_available_server()
  18. return this.servers
  19. }
  20. check(): void {
  21. console.log('Checking servers first …')
  22. console.log(this.servers)
  23. // check servers for connectivity and if the secret is correct
  24. this.servers.forEach(async s => {
  25. const hash = createHash("sha1");
  26. hash.update(`getMeetings${s.secret}`)
  27. try {
  28. // throw an error if cannot connect or if secret fails
  29. const res = await fetch(`${s.host}/bigbluebutton/api/getMeetings?checksum=${hash.toString()}`)
  30. if (!res.ok) throw "Connection error. Please check your host configuration"
  31. const body = await res.text()
  32. const ok = body.includes('SUCCESS')
  33. console.log(`${s.host} is ${ok ? Color.green('ok') : Color.red('misconfigured. Please check your secret in servers.json')}`)
  34. if (!ok) throw "Configuration error. Exiting …"
  35. } catch (e) {
  36. // exit tinyscale if an error is encountered in servers.json
  37. console.log(Color.brightRed(JSON.stringify(e)))
  38. Deno.exit(1);
  39. }
  40. })
  41. }
  42. // pick the next server, using an iterator to cycle through all servers available
  43. get_available_server(): server {
  44. let candidate = this.iterator.next()
  45. if (candidate.done) {
  46. this.iterator = this.servers[Symbol.iterator]()
  47. candidate = this.iterator.next()
  48. }
  49. this.current_server = candidate.value;
  50. return this.current_server
  51. }
  52. }