os#hostname TypeScript Examples

The following examples show how to use os#hostname. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: print.ts    From discord with GNU General Public License v3.0 6 votes vote down vote up
export default async function (i: GenericInteraction): Promise<InteractionApplicationCommandCallbackData> {
  try {
    const data = await Database
      .collection('guilds')
      .findOne({ _id: Long.fromString(i.guild_id) })

    data._ = {
      shard: ((typeof i.guildData.sharder === 'number') ? i.guildData.sharder : i.guildData.sharder.getLowBits()) % Core.options.shardCount,
      worker: Manager.getSelfUUID(),
      container: await hostname()
    }

    const description = '```json\n' + JSON.stringify(data, null, 2) + '```'

    return {
      title: 'Guild Data Print',
      description,
      components: [
        {
          type: ComponentType.BUTTON,
          style: ButtonStyle.SECONDARY,
          custom_id: 'admin_main',
          label: '=generic_back',
          emoji: { id: Emojis.caretLeft.id }
        }
      ]
    }
  } catch (ex) {
    return {
      title: 'Error',
      description: '```' + ex + '```'
    }
  }
}
Example #2
Source File: manager.ts    From discord with GNU General Public License v3.0 6 votes vote down vote up
private static async openSocket() {
    Logger.excessive('Manager#openSocket')
    if (config.mode.name !== 'worker') return // for type safety below

    const socketHost = config.mode.master.host || this.DEFAULT_SOCKET_HOST
    const socketPath = config.mode.master.path || this.DEFAULT_SOCKET_PATH
    const gitCommit = await getGitCommit()

    this.socket = io(socketHost, {
      reconnectionDelayMax: 10000,
      reconnectionDelay: 1000,
      query: {
        type: 'worker',
        version: gitCommit.hash,
        container: hostname(),
        node: process.env.NODE_ID,
        id: this.selfUUID
      },
      path: socketPath,
      jsonp: false,
      transports: [ 'websocket' ],
      auth: {
        key: config.mode.master.auth || config.apiSettings.key
      }
    })

    this.prepareSocket()
    this.connectSocket()
  }
Example #3
Source File: guilddata-visualizer.ts    From discord with GNU General Public License v3.0 6 votes vote down vote up
export default function guildDataToViewString(g: GuildData, maxLength = 2048, errorMessage?: string, includeMetainfo = false) {
  const gd = { ...g } as any
  if (gd) {
    delete gd.channelInstance
    delete gd.roleInstance
    if (includeMetainfo) {
      gd.host = hostname()
      gd.workerIndex = Manager.getMeta().workerIndex
      gd.shard = ((typeof g.sharder === 'number') ? g.sharder : g.sharder.getLowBits()) % Core.options.shardCount
    }

    gd.currency = gd.currency.name
    gd.price = gd.price.name
    gd.theme = gd.theme.name
    gd.platformsList = gd.platformsList.map(p => p.id)
    gd.trackerList = Object
      .entries(Tracker.TRACKING_POINT)
      .filter(v => (gd.tracker & v[1]) !== 0)
      .map(v => v[0])
  }

  let guilddata = `\`\`\`json\n${JSON.stringify(gd || { error: 'Guild Data Error' }, null, 2)}\`\`\``
  if (guilddata.length > maxLength) guilddata = `\`\`\`json\n${JSON.stringify(gd || { error: 'Guild Data Error' }, null, 1)}\`\`\``
  if (guilddata.length > maxLength) guilddata = `\`\`\`json\n${JSON.stringify(gd || { error: 'Guild Data Error' })}\`\`\``
  if (guilddata.length > maxLength) {
    Logger.log(JSON.stringify(gd, null, 2))
    guilddata = errorMessage || 'Guild data too long. Check logs.'
  }

  return guilddata
}
Example #4
Source File: sentry.ts    From discord with GNU General Public License v3.0 6 votes vote down vote up
public static init() {
    if (config.bot.mode !== 'regular') {
      Logger.process('Skipping Sentry initialization. Reason: config.bot.mode != "regular"')
      return
    }

    if (!config.thirdParty?.sentry?.dsn) {
      Logger.process('Skipping Sentry initialization. Reason: no config found')
      return
    }

    Logger.process('Initializing Sentry ...')

    Sentry.init({
      dsn: config.thirdParty.sentry.dsn,
      serverName: hostname(),
      beforeSend: async (event, hint) => {
        let err = (hint.originalException?.toString() || hint.syntheticException.message) as any
        if ('then' in err) err = await err
        Logger.warn('sentry <> ' + err)
        return event
      }
    })

    Logger.process('Sentry initialized')
  }
Example #5
Source File: event-store.publisher.ts    From nestjs-geteventstore with MIT License 6 votes vote down vote up
protected getStreamName(
    correlationId: EventBase['metadata']['correlation_id'],
  ): string {
    const defaultName = process.argv?.[1]
      ? basename(process.argv?.[1], extname(process.argv?.[1]))
      : `${hostname()}_${process.argv?.[0] || 'unknown'}`;

    return `${this.config.serviceName || defaultName}-${correlationId}`;
  }
Example #6
Source File: db.ts    From livepeer-com with MIT License 6 votes vote down vote up
async start({
    postgresUrl,
    postgresReplicaUrl,
    appName = "api",
  }: PostgresParams) {
    this.postgresUrl = postgresUrl;
    if (!postgresUrl) {
      throw new Error("no postgres url provided");
    }
    try {
      await ensureDatabase(postgresUrl);
    } catch (e) {
      console.error(`error in ensureDatabase: ${e.message}`);
      throw e;
    }
    this.pool = new Pool({
      connectionTimeoutMillis: CONNECT_TIMEOUT,
      connectionString: postgresUrl,
      application_name: `${appName}-${hostname()}`,
    });

    if (postgresReplicaUrl) {
      console.log("replica url found, using read replica");
      this.replicaPool = new Pool({
        connectionTimeoutMillis: CONNECT_TIMEOUT,
        connectionString: postgresReplicaUrl,
        application_name: `${appName}-read-${hostname()}`,
      });
    } else {
      console.log("no replica url found, not using read replica");
    }

    await this.query("SELECT NOW()");
    await this.replicaQuery("SELECT NOW()");
    await this.makeTables();
  }
Example #7
Source File: more.ts    From discord with GNU General Public License v3.0 5 votes vote down vote up
export default function (i: GenericInteraction): InteractionApplicationCommandCallbackData {
  Tracker.set(i.guildData, 'PAGE_DISCOVERED_SETTINGS_CHANGE_MORE')

  const sharder = (typeof i.guildData.sharder === 'number') ? i.guildData.sharder : i.guildData.sharder.getLowBits()
  const debugInfo = `\n\n**Debug info:** Shard \`${sharder % Core.options.shardCount}\` ─ Worker \`${Manager.getSelfUUID()}\` ─ Container \`${hostname() || 'unknown'}\` ─ Node \`${process.env.NODE_ID}\` ─ Version \`${VERSION}\` ─ Guildid \`${i.guild_id}\` ─ Migrated \`${!!i.guildData?.webhook}\``

  return {
    title: '=settings_more_ui_1',
    description: Localisation.text(i.guildData, '=settings_more_ui_2') + debugInfo,
    components: [
      {
        type: ComponentType.BUTTON,
        style: ButtonStyle.SECONDARY,
        custom_id: 'settings_run_test',
        label: '=settings_more_btn_test',
        flags: [ InteractionComponentFlag.ACCESS_MANAGE_SERVER ]
      },
      {
        type: ComponentType.BUTTON,
        style: ButtonStyle.SECONDARY,
        custom_id: 'settings_run_resend',
        label: '=settings_more_btn_resend',
        flags: [ InteractionComponentFlag.ACCESS_MANAGE_SERVER ]
      },
      {
        type: ComponentType.LINE_BREAK
      },
      {
        type: ComponentType.BUTTON,
        style: ButtonStyle.SECONDARY,
        custom_id: 'settings_main',
        label: '=generic_back',
        emoji: { id: Emojis.caretLeft.id }
      },
      {
        type: ComponentType.BUTTON,
        style: ButtonStyle.SECONDARY,
        custom_id: 'settings_guilddata',
        label: '=settings_more_btn_guilddata',
        flags: [ InteractionComponentFlag.ACCESS_EVERYONE, InteractionComponentFlag.ACCESS_MANAGE_SERVER ]
      },
      {
        type: ComponentType.BUTTON,
        style: i.guildData?.beta ? ButtonStyle.SUCCESS : ButtonStyle.SECONDARY,
        custom_id: 'settings_beta_toggle',
        label: i.guildData?.beta ? '=settings_more_beta_on_state' : '=settings_more_beta_on_prompt',
        flags: [ InteractionComponentFlag.ACCESS_MANAGE_SERVER ]
      }
    ]
  }
}
Example #8
Source File: manager.ts    From discord with GNU General Public License v3.0 5 votes vote down vote up
private static generateSelfUUID(): string {
    const host = hostname()
    const timestamp = Date.now().toString(32)
    const random = Util.generateWord('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', 6)
    return `${host}.${timestamp}.${random}`
  }
Example #9
Source File: build-winston-logger.ts    From metroline with GNU General Public License v3.0 5 votes vote down vote up
host = hostname()
Example #10
Source File: stream-info-app.ts    From livepeer-com with MIT License 5 votes vote down vote up
constructor(broadcaster: string, region: string) {
    this.broadcaster = broadcaster;
    this.region = region;
    this.seenStreams = new Map<string, streamInfo>();
    this.hostname = hostname();
  }
Example #11
Source File: stream-info-app.ts    From livepeer-com with MIT License 5 votes vote down vote up
hostname: string;
Example #12
Source File: http-server.ts    From sdkgen with MIT License 4 votes vote down vote up
private writeReply(res: ServerResponse, ctx: Context | null, reply: ContextReply, hrStart: [number, number]) {
    if (!ctx) {
      res.statusCode = 500;
      res.write(
        JSON.stringify({
          error: this.makeResponseError(reply.error ?? new Fatal("Response without context")),
        }),
      );
      res.end();
      return;
    }

    const deltaTime = process.hrtime(hrStart);
    const duration = deltaTime[0] + deltaTime[1] * 1e-9;

    if (reply.error) {
      console.error(reply.error);
    }

    this.log(`${ctx.request.id} [${duration.toFixed(6)}s] ${ctx.request.name}() -> ${reply.error ? this.makeResponseError(reply.error).type : "OK"}`);

    if (ctx.response.statusCode) {
      res.statusCode = ctx.response.statusCode;
    }

    for (const [headerKey, headerValue] of ctx.response.headers.entries()) {
      res.setHeader(headerKey, headerValue);
    }

    switch (ctx.request.version) {
      case 1: {
        const response = {
          deviceId: ctx.request.deviceInfo.id,
          duration,
          error: reply.error ? this.makeResponseError(reply.error) : null,
          host: hostname(),
          id: ctx.request.id,
          ok: !reply.error,
          result: reply.error ? null : reply.result,
        };

        if (response.error && !ctx.response.statusCode) {
          res.statusCode = this.makeResponseError(response.error).type === "Fatal" ? 500 : 400;
        }

        res.write(JSON.stringify(response));
        res.end();
        break;
      }

      case 2: {
        const response = {
          deviceId: ctx.request.deviceInfo.id,
          error: reply.error ? this.makeResponseError(reply.error) : null,
          ok: !reply.error,
          requestId: ctx.request.id,
          result: reply.error ? null : reply.result,
          sessionId: ctx.request.extra.sessionId,
        };

        if (response.error && !ctx.response.statusCode) {
          res.statusCode = this.makeResponseError(response.error).type === "Fatal" ? 500 : 400;
        }

        res.write(JSON.stringify(response));
        res.end();
        break;
      }

      case 3: {
        const response = {
          duration,
          error: reply.error ? this.makeResponseError(reply.error) : null,
          host: hostname(),
          result: reply.error ? null : reply.result,
        };

        if (response.error && !ctx.response.statusCode) {
          res.statusCode = this.makeResponseError(response.error).type === "Fatal" ? 500 : 400;
        }

        res.setHeader("x-request-id", ctx.request.id);
        res.write(JSON.stringify(response));
        res.end();
        break;
      }

      default: {
        res.statusCode = 500;
        res.write(
          JSON.stringify({
            error: this.makeResponseError(reply.error ?? new Fatal("Unknown request version")),
          }),
        );
        res.end();
        return;
      }
    }
  }
Example #13
Source File: cli.ts    From Assistive-Webdriver with MIT License 4 votes vote down vote up
(async function () {
  const argv = await yargs.options({
    browser: {
      array: true,
      type: "string",
      alias: "b",
      default: ["chromium"]
    },
    "log-level": {
      type: "string",
      alias: "l",
      default: "info"
    },
    "public-host": {
      type: "string",
      alias: "h",
      default: `${hostname()}.`
    },
    "listen-host": {
      type: "string",
      default: "0.0.0.0"
    },
    "public-port": {
      type: "number",
      alias: "p",
      default: 0
    },
    "listen-port": {
      type: "number",
      default: 0
    },
    "vm-settings": {
      type: "string",
      alias: "m",
      demandOption: true
    },
    "server-port": {
      type: "number",
      default: 7779
    },
    "skip-keys": {
      type: "array",
      alias: "k"
    },
    "screen-reader": {
      type: "boolean",
      default: true
    }
  }).argv;
  configure({
    level: argv["log-level"] as any,
    format: format.combine(format.colorize(), format.simple()),
    transports: [new transports.Console()]
  });

  const vmSettings = JSON.parse(argv["vm-settings"]);
  info(`Starting the VM...`);
  const driver = await createVM({
    log: (entry: any) => log(entry),
    vmSettings,
    playwrightPort: argv["server-port"]
  });
  const availableBrowsers: {
    [name: string]:
      | BrowserType<ChromiumBrowser>
      | BrowserType<FirefoxBrowser>
      | BrowserType<WebKitBrowser>;
  } = {
    chromium: driver.chromium,
    firefox: driver.firefox,
    webkit: driver.webkit
  };
  const screenReader = argv["screen-reader"];
  const testerSession = new TesterSession(driver, screenReader);
  let vmDestroyed = false;

  process.on("SIGINT", async () => {
    if (!vmDestroyed) {
      warn("Stopping the VM...");
      vmDestroyed = true;
      await driver.vm.destroy();
      error("Tests were interrupted.");
      process.exit(2);
    }
  });
  sigintWin32();

  try {
    const eventsServerAddress = await new Promise<AddressInfo>(
      (resolve, reject) =>
        testerSession.eventsServer
          .listen(
            argv["listen-port"] || argv["public-port"],
            argv["listen-host"] || argv["public-host"],
            () => {
              resolve(testerSession.eventsServer.address() as AddressInfo);
            }
          )
          .once("error", reject)
    );

    const eventsServerListenAddress = `http://${eventsServerAddress.address}:${eventsServerAddress.port}`;
    const publicPort = argv["public-port"] || eventsServerAddress.port;
    const publicHost = argv["public-host"] || eventsServerAddress.address;
    const eventsServerPublicAddress = `http://${publicHost}:${publicPort}`;
    info(
      `Test page server started at ${eventsServerListenAddress}, VM will connect to ${eventsServerPublicAddress}`
    );
    if (screenReader) {
      info("Screen reader testing is ENABLED.");
      driver.screenReader.on("message", message =>
        info(`Screen reader said: ${message}`)
      );
    } else {
      info("Screen reader testing is DISABLED.");
    }

    for (const browserName of argv.browser) {
      const browser = availableBrowsers[browserName];
      if (!browser) {
        testerSession.reportError(`Unknown browser: ${browserName}`);
        continue;
      }
      info(`Testing on browser ${browserName}`);
      const browserInstance = await browser.launch({ headless: false });
      try {
        const page = await browserInstance.newPage({
          viewport: null
        });
        testerSession.page = page;
        const mouse = await driver.calibrateMouse(page);
        testerSession.mouse = mouse;
        info(`Loading test page from ${eventsServerPublicAddress}`);
        const response = await page.goto(eventsServerPublicAddress);
        if (!response?.ok) {
          testerSession.reportError(
            `Could not successfully load page ${eventsServerPublicAddress}`
          );
          continue;
        }
        info(`Test page was successfully loaded`);

        const testInput = await page.$("#testInput");
        await mouse.click(0, 0, { origin: testInput });
        await page.waitForFunction(hasFocus, testInput);

        if (screenReader) {
          await driver.screenReader.clearMessages();
        }

        await driver.keyboard.press(Key.Tab);

        if (screenReader) {
          try {
            await driver.screenReader.waitForMessage("mysupertestlabeltocheck");
          } catch (e) {
            testerSession.reportError(`Screen reader test failed: ${e}`);
          }
        }

        const testDiv = await page.$("#testDiv");
        await page.waitForFunction(hasFocus, testDiv);

        await testerSession.eventsQueue.getAllWaitingValues();

        await testAllKeys(testerSession, argv["skip-keys"] as any);
        await testMouseButtons(testerSession);
      } catch (error: any) {
        testerSession.reportError(`${error.stack || error.message || error}`);
        continue;
      } finally {
        try {
          info(`Closing browser ${browserName}...`);
          await browserInstance.close();
        } catch (e) {
          console.log(`Error in browserInstance.close()`);
        }
        info(`Tests finished for browser ${browserName}`);
      }
    }

    if (testerSession.errorsNumber === 0) {
      info("All tests were successful!");
    } else {
      throw "Some tests failed!";
    }
  } finally {
    await collectCoverage(driver.url);
    testerSession.reportMeasures();
    vmDestroyed = true;
    await driver.vm.destroy();
    testerSession.eventsServer.close();
  }
})().catch(e => {
  error(`${e.stack || e.message || e}`);
  process.exit(1);
});
Example #14
Source File: http-client.ts    From sdkgen with MIT License 4 votes vote down vote up
async makeRequest(ctx: PartialDeep<Context> | null, functionName: string, args: unknown): Promise<any> {
    const func = this.astJson.functionTable[functionName];

    if (!func) {
      throw new Error(`Unknown function ${functionName}`);
    }

    const extra: Record<string, unknown> = {};

    for (const [key, value] of this.extra) {
      extra[key] = value;
    }

    const requestBody = JSON.stringify({
      args: encode(this.astJson.typeTable, `${functionName}.args`, func.args, args),
      deviceInfo: ctx?.request?.deviceInfo ?? { id: hostname(), type: "node" },
      extra: {
        ...extra,
        ...ctx?.request?.extra,
      },
      name: functionName,
      requestId: ctx?.request?.id ? ctx.request.id + randomBytes(6).toString("hex") : randomBytes(16).toString("hex"),
      version: 3,
    });

    const options: RequestOptions = {
      hostname: this.baseUrl.hostname,
      method: "POST",
      path: this.baseUrl.pathname,
      port: this.baseUrl.port,
      headers: {
        "content-type": "application/sdkgen",
      },
    };

    const encodedRet = await new Promise<unknown>((resolve, reject) => {
      const req = (this.baseUrl.protocol === "http:" ? httpRequest : httpsRequest)(options, res => {
        let data = "";

        res.on("data", chunk => {
          data += chunk;
        });
        res.on("end", () => {
          try {
            const response = JSON.parse(data) as object;

            if (has(response, "error") && response.error) {
              reject(response.error);
            } else {
              resolve(has(response, "result") ? response.result : null);
            }
          } catch (error) {
            reject({ message: `${error}`, type: "Fatal" });
          }
        });
        res.on("error", error => {
          reject({ message: `${error}`, type: "Fatal" });
        });
        res.on("aborted", () => {
          reject({ message: "Request aborted", type: "Fatal" });
        });
      });

      req.on("error", error => {
        reject({ message: `${error}`, type: "Fatal" });
      });

      req.write(requestBody);
      req.end();
    }).catch(error => {
      if (has(error, "type") && has(error, "message") && typeof error.type === "string" && typeof error.message === "string") {
        const errClass = this.errClasses[error.type];

        if (errClass) {
          const errorJson = this.astJson.errors.find(err => (Array.isArray(err) ? err[0] === error.type : err === error.type));

          if (errorJson) {
            if (Array.isArray(errorJson) && has(error, "data")) {
              throw new errClass(error.message, decode(this.astJson.typeTable, `${errClass.name}.data`, errorJson[1], error.data));
            } else {
              throw new errClass(error.message, undefined);
            }
          }
        }

        throw new (this.errClasses.Fatal as new (message: string) => SdkgenError)(`${error.type}: ${error.message}`);
      } else {
        throw error;
      }
    });

    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return decode(this.astJson.typeTable, `${functionName}.ret`, func.ret, encodedRet);
  }
Example #15
Source File: stream-info-app.ts    From livepeer-com with MIT License 4 votes vote down vote up
private async pollStatus() {
    // console.log(`Polling b ${this.broadcaster} `)
    let status;
    try {
      status = await this.getStatus(this.broadcaster);
    } catch (e) {
      if (e.code !== "ECONNREFUSED") {
        console.log(`got error fetch status: `, e);
      }
      return;
    }
    // console.log(`got status: `, status)
    const playback2session = new Map<string, string>();
    for (const k of Object.keys(status.InternalManifests || {})) {
      playback2session.set(status.InternalManifests[k], k);
    }
    const getObjectByMid = async (mid: string): Promise<Stream | null> => {
      const sid = playback2session.has(mid) ? playback2session.get(mid) : mid;
      let storedInfo: Stream = await db.stream.get(sid);
      if (!storedInfo) {
        const [objs, _] = await db.stream.find({ playbackId: mid });
        if (objs?.length) {
          storedInfo = objs[0];
        }
      }
      return storedInfo;
    };
    const now = new Date();
    for (const mid of Object.keys(status.Manifests)) {
      let si,
        timeSinceLastSeen = 0,
        needUpdate = false;
      if (!this.seenStreams.has(mid)) {
        // new stream
        // console.log(`got new stream ${mid}`)
        si = newStreamInfo();
        this.seenStreams.set(mid, si);
        needUpdate = true;
      } else {
        si = this.seenStreams.get(mid);
        needUpdate = now.valueOf() - si.lastUpdated.valueOf() > updateInterval;
        timeSinceLastSeen = (now.valueOf() - si.lastSeen.valueOf()) / 1000;
        si.lastSeen = now;
      }
      if (mid in (status.StreamInfo || {})) {
        const statusStreamInfo = status.StreamInfo[mid];
        if (
          si.sourceBytes > 0 &&
          statusStreamInfo.SourceBytes > si.sourceBytes &&
          timeSinceLastSeen > 0
        ) {
          si.ingestRate =
            (statusStreamInfo.SourceBytes - si.sourceBytes) / timeSinceLastSeen;
        }
        if (
          si.transcodedBytes > 0 &&
          statusStreamInfo.TranscodedBytes > si.transcodedBytes &&
          timeSinceLastSeen > 0
        ) {
          si.outgoingRate =
            (statusStreamInfo.TranscodedBytes - si.transcodedBytes) /
            timeSinceLastSeen;
        }
        si.sourceBytes = statusStreamInfo.SourceBytes;
        si.transcodedBytes = statusStreamInfo.TranscodedBytes;
      }
      const manifest = status.Manifests[mid];
      countSegments(si, manifest);
      if (needUpdate) {
        const storedInfo: Stream = await getObjectByMid(mid);
        // console.log(`got stream info from store: `, storedInfo)
        // console.log(`---> manifest`, JSON.stringify(manifest, null, 2))
        // console.log(`---> si:`, si)
        if (storedInfo) {
          si.objectId = storedInfo.id;
          si.lastSeenSavedToDb = si.lastSeen;
          const setObj = {
            lastSeen: si.lastSeen.valueOf(),
            ingestRate: si.ingestRate,
            outgoingRate: si.outgoingRate,
            broadcasterHost: this.hostname,
          } as Stream;
          const incObj = {
            sourceSegments: si.sourceSegments - si.sourceSegmentsLastUpdated,
            transcodedSegments:
              si.transcodedSegments - si.transcodedSegmentsLastUpdated,
            sourceSegmentsDuration:
              si.sourceSegmentsDuration - si.sourceSegmentsDurationLastUpdated,
            transcodedSegmentsDuration:
              si.transcodedSegmentsDuration -
              si.transcodedSegmentsDurationLastUpdated,
            sourceBytes: si.sourceBytes - si.sourceBytesLastUpdated,
            transcodedBytes: si.transcodedBytes - si.transcodedBytesLastUpdated,
          };
          if (!storedInfo.parentId && !playback2session.has(mid)) {
            // this is not a session created by our Mist, so manage isActive field for this stream
            setObj.isActive = true;
            setObj.region = this.region;
          }
          // console.log(`---> setting`, setObj)
          // console.log(`---> inc`, incObj)
          await db.stream.update(storedInfo.id, setObj);
          await db.stream.add(storedInfo.id, incObj as Stream);
          if (storedInfo.parentId) {
            await db.stream.add(storedInfo.parentId, incObj as Stream);
            await db.stream.update(storedInfo.parentId, setObj);
            const userSessionId = getSessionId(storedInfo);
            // update session table
            try {
              await db.session.add(userSessionId, incObj as Stream);
              await db.session.update(userSessionId, setObj);
            } catch (e) {
              console.log(`error updating session table:`, e);
            }
          }
          si.lastUpdated = new Date();
          si.sourceSegmentsLastUpdated = si.sourceSegments;
          si.transcodedSegmentsLastUpdated = si.transcodedSegments;
          si.sourceSegmentsDurationLastUpdated = si.sourceSegmentsDuration;
          si.transcodedSegmentsDurationLastUpdated =
            si.transcodedSegmentsDuration;
          si.sourceBytesLastUpdated = si.sourceBytes;
          si.transcodedBytesLastUpdated = si.transcodedBytes;
        }
      }
    }
    for (const [mid, si] of this.seenStreams) {
      const now = Date.now();
      if (!(mid in status.Manifests)) {
        const notSeenFor: number = now - si.lastSeen.valueOf();
        if (notSeenFor > deleteTimeout) {
          this.seenStreams.delete(mid);
          const storedInfo: Stream = await getObjectByMid(si.objectId || mid);
          if (storedInfo) {
            const zeroRate = {
              ingestRate: 0,
              outgoingRate: 0,
            } as Stream;
            await db.stream.update(storedInfo.id, zeroRate);
            if (storedInfo.parentId) {
              await db.stream.update(storedInfo.parentId, zeroRate);
              const userSessionId = getSessionId(storedInfo);
              await db.session.update(userSessionId, zeroRate);
            }
            if (!storedInfo.parentId) {
              // this is not a session created by our Mist, so manage isActive field for this stream
              await db.stream.setActiveToFalse({
                id: storedInfo.id,
                lastSeen: si.lastSeenSavedToDb.valueOf(),
              });
            }
          }
        }
        // console.log(`seen: `, this.seenStreams)
      }
    }
  }
Example #16
Source File: Config.ts    From fosscord-server with GNU Affero General Public License v3.0 4 votes vote down vote up
DefaultConfigOptions: ConfigValue = {
	gateway: {
		endpointClient: null,
		endpointPrivate: null,
		endpointPublic: null,
	},
	cdn: {
		endpointClient: null,
		endpointPrivate: null,
		endpointPublic: null,
	},
	api: {
		defaultVersion: "9",
		activeVersions: ["6", "7", "8", "9"],
		useFosscordEnhancements: true,
	},
	general: {
		instanceName: "Fosscord Instance",
		instanceDescription: "This is a Fosscord instance made in pre-release days",
		frontPage: null,
		tosPage: null,
		correspondenceEmail: "[email protected]",
		correspondenceUserID: null,
		image: null,
		instanceId: Snowflake.generate(),
	},
	limits: {
		user: {
			maxGuilds: 100,
			maxUsername: 32,
			maxFriends: 1000,
		},
		guild: {
			maxRoles: 250,
			maxEmojis: 50, // TODO: max emojis per guild per nitro level
			maxMembers: 250000,
			maxChannels: 500,
			maxChannelsInCategory: 50,
			hideOfflineMember: 1000,
		},
		message: {
			maxCharacters: 2000,
			maxTTSCharacters: 200,
			maxReactions: 20,
			maxAttachmentSize: 8388608,
			maxBulkDelete: 100,
		},
		channel: {
			maxPins: 50,
			maxTopic: 1024,
			maxWebhooks: 10,
		},
		rate: {
			disabled: true,
			ip: {
				count: 500,
				window: 5,
			},
			global: {
				count: 20,
				window: 5,
				bot: 250,
			},
			error: {
				count: 10,
				window: 5,
			},
			routes: {
				guild: {
					count: 5,
					window: 5,
				},
				webhook: {
					count: 10,
					window: 5,
				},
				channel: {
					count: 10,
					window: 5,
				},
				auth: {
					login: {
						count: 5,
						window: 60,
					},
					register: {
						count: 2,
						window: 60 * 60 * 12,
					},
				},
			},
		},
	},
	security: {
		autoUpdate: true,
		requestSignature: crypto.randomBytes(32).toString("base64"),
		jwtSecret: crypto.randomBytes(256).toString("base64"),
		forwadedFor: null,
		// forwadedFor: "X-Forwarded-For" // nginx/reverse proxy
		// forwadedFor: "CF-Connecting-IP" // cloudflare:
		captcha: {
			enabled: false,
			service: null,
			sitekey: null,
			secret: null,
		},
		ipdataApiKey: "eca677b284b3bac29eb72f5e496aa9047f26543605efe99ff2ce35c9",
	},
	login: {
		requireCaptcha: false,
	},
	register: {
		email: {
			required: false,
			allowlist: false,
			blocklist: true,
			domains: [], // TODO: efficiently save domain blocklist in database
			// domains: fs.readFileSync(__dirname + "/blockedEmailDomains.txt", { encoding: "utf8" }).split("\n"),
		},
		dateOfBirth: {
			required: true,
			minimum: 13,
		},
		disabled: false,
		requireInvite: false,
		guestsRequireInvite: true,
		requireCaptcha: true,
		allowNewRegistration: true,
		allowMultipleAccounts: true,
		blockProxies: true,
		password: {
			required: false,
			minLength: 8,
			minNumbers: 2,
			minUpperCase: 2,
			minSymbols: 0,
		},
		incrementingDiscriminators: false,
	},
	regions: {
		default: "fosscord",
		useDefaultAsOptimal: true,
		available: [
			{
				id: "fosscord",
				name: "Fosscord",
				endpoint: "127.0.0.1:3004",
				vip: false,
				custom: false,
				deprecated: false,
			},
		],
	},
	guild: {
		discovery: {
			showAllGuilds: false,
			useRecommendation: false,
			offset: 0,
			limit: 24,
		},
		autoJoin: {
			enabled: true,
			canLeave: true,
			guilds: [],
		},
	},
	gif: {
		enabled: true,
		provider: "tenor",
		apiKey: "LIVDSRZULELA",
	},
	rabbitmq: {
		host: null,
	},
	kafka: {
		brokers: null,
	},
	templates: {
		enabled: true,
		allowTemplateCreation: true,
		allowDiscordTemplates: true,
		allowRaws: false
	},
	client: {
		useTestClient: true,
		releases: {
			useLocalRelease: true,
			upstreamVersion: "0.0.264"
		}
	},
	metrics: {
		timeout: 30000
	},
	sentry: {
		enabled: false,
		endpoint: "https://[email protected]/6",
		traceSampleRate: 1.0,
		environment: hostname()
	}
}
Example #17
Source File: bin.ts    From Assistive-Webdriver with MIT License 4 votes vote down vote up
(async function () {
  const argv = await yargs.options({
    server: {
      type: "string",
      alias: "s",
      default: "http://localhost:3000"
    },
    browser: {
      type: "string",
      alias: "b",
      default: Browser.CHROME
    },
    capabilities: {
      type: "string",
      default: "{}"
    },
    "log-level": {
      type: "string",
      alias: "l",
      default: "info"
    },
    "public-host": {
      type: "string",
      alias: "h",
      default: `${hostname()}.`
    },
    "listen-host": {
      type: "string",
      default: "0.0.0.0"
    },
    "public-port": {
      type: "number",
      alias: "p",
      default: 0
    },
    "listen-port": {
      type: "number",
      default: 0
    },
    "vm-config": {
      type: "string",
      alias: "m"
    },
    "skip-keys": {
      type: "array",
      alias: "k"
    }
  }).argv;
  configure({
    level: argv["log-level"] as any,
    format: format.combine(format.colorize(), format.simple()),
    transports: [new transports.Console()]
  });

  const capabilities = JSON.parse(argv.capabilities);
  if (argv["vm-config"]) {
    capabilities["awd:vm-config"] = argv["vm-config"];
  }
  info(`Connecting to webdriver server at ${argv.server}`, {
    capabilities,
    browser: argv.browser
  });

  const driver = await new Builder()
    .withCapabilities(capabilities)
    .forBrowser(argv.browser)
    .usingServer(argv.server)
    .build();

  process.on("SIGINT", async () => {
    warn("Closing the session...");
    await driver.quit();
    error("Tests were interrupted.");
    process.exit(2);
  });
  sigintWin32();

  const testerSession = new TesterSession(driver);
  try {
    const eventsServerAddress = await new Promise<AddressInfo>(
      (resolve, reject) =>
        testerSession.eventsServer
          .listen(
            argv["listen-port"] || argv["public-port"],
            argv["listen-host"] || argv["public-host"],
            () => {
              resolve(testerSession.eventsServer.address() as AddressInfo);
            }
          )
          .once("error", reject)
    );

    const eventsServerListenAddress = `http://${eventsServerAddress.address}:${eventsServerAddress.port}`;
    const publicPort = argv["public-port"] || eventsServerAddress.port;
    const publicHost = argv["public-host"] || eventsServerAddress.address;
    const eventsServerPublicAddress = `http://${publicHost}:${publicPort}`;
    info(
      `Test page server started at ${eventsServerListenAddress}, VM will connect to ${eventsServerPublicAddress}`
    );
    try {
      await refreshScreenReaderText(testerSession.driver);
      info("Screen reader testing is ENABLED.");
      addScreenReaderTextListener(testerSession.driver, message =>
        info(`Screen reader said: ${message}`)
      );
      testerSession.screenReader = true;
    } catch (error) {
      info("Screen reader testing is DISABLED.");
    }
    info(`Loading test page from ${eventsServerPublicAddress}`);
    await driver.get(eventsServerPublicAddress);
    const body = await driver.findElement(By.css("body"));
    await driver.wait(until.elementTextContains(body, "ready"));
    info(`Test page was successfully loaded`);

    const testInput = await driver.findElement(By.css("#testInput"));

    await driver.actions().click(testInput).perform();

    await driver.wait(untilElementHasFocus(testInput), 10000);

    if (testerSession.screenReader) {
      await clearCachedScreenReaderText(testerSession.driver);
    }

    await driver.actions().keyDown(Key.TAB).keyUp(Key.TAB).perform();

    if (testerSession.screenReader) {
      try {
        await testerSession.driver.wait(
          forScreenReaderToSay("mysupertestlabeltocheck"),
          5000
        );
      } catch (e) {
        testerSession.reportError(`Screen reader test failed: ${e}`);
      }
    }

    const testDiv = await driver.findElement(By.css("#testDiv"));
    await driver.wait(untilElementHasFocus(testDiv), 10000);

    await testerSession.eventsQueue.getAllWaitingValues();

    await testAllKeys(testerSession, argv["skip-keys"] as any);
    await testMouseButtons(testerSession);

    if (testerSession.errorsNumber === 0) {
      info("All tests were successful!");
    } else {
      throw new Error("Some tests failed!");
    }
  } finally {
    testerSession.reportMeasures();
    await driver.quit();
    testerSession.eventsServer.close();
  }
})().catch(e => {
  error(`${e}`);
  process.exit(1);
});