repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
angelxehg/angelxehg.github.io
src/pages/index.tsx
import React from "react" import SEO from "../components/SEO" import Layout from "../layouts/Layout" import { HugeHeader } from "../components/Header" import DefaultFooter from "../components/Footer" import DefaultNavbar from "../components/Navbar" import { AboutSection } from "./about" import { SkillsSection } from "./skills" import { ProjectsSection } from "./projects" import { PostsSection } from "./posts" const IndexPage = (): JSX.Element => ( <Layout> <SEO title="Portafolio" lang="es" /> <DefaultNavbar /> <HugeHeader /> <main className="container-lg ps-sm-4 pe-sm-4 pb-3"> <AboutSection /> <SkillsSection /> <ProjectsSection /> <PostsSection /> </main> <DefaultFooter /> </Layout> ) export default IndexPage
angelxehg/angelxehg.github.io
src/meta/data/generic.ts
import { LinkMeta } from "../types" export const genericWebLink: LinkMeta = { name: "Web", icon: { svgPath: "bootstrap-icons/globe2.svg", }, href: "https://angelxehg.github.io/", } const generics: LinkMeta[] = [ { name: "Day", icon: { svgPath: "bootstrap-icons/sun.svg", }, href: "https://angelxehg.github.io/", }, { name: "Night", icon: { svgPath: "bootstrap-icons/moon.svg", }, href: "https://angelxehg.github.io/", }, { name: "File", icon: { svgPath: "bootstrap-icons/file-earmark-text-fill.svg", }, href: "https://angelxehg.github.io/", }, { name: "Email", icon: { svgPath: "bootstrap-icons/envelope-fill.svg", }, href: "https://angelxehg.github.io/", }, genericWebLink, ] export default generics
angelxehg/angelxehg.github.io
src/meta/data/tools.ts
<filename>src/meta/data/tools.ts<gh_stars>0 import { LinkMeta } from "../types" const tools: LinkMeta[] = [ { name: "Cordova", icon: { svgPath: "seek-logo/cordova.svg", style: { backgroundColor: "white", borderRadius: "15%", padding: "0.05rem", }, }, href: "https://fontawesome.com/license", }, { name: "FontAwesome", displayName: "Font Awesome", icon: { svgPath: "seek-logo/font-awesome.svg", style: { backgroundColor: "white", borderRadius: "15%", }, }, href: "https://fontawesome.com/license", }, { name: "Git", icon: { style: { color: "#E94E31" }, svgPath: "seek-logo/git.svg", }, href: "https://git-scm.com/", }, { name: "NodeJS", displayName: "Node.js", icon: { style: { color: "#7FC728", backgroundColor: "#333", borderRadius: "50%", padding: "0.05rem", }, svgPath: "fontawesome/node-js-brands.svg", }, href: "https://nodejs.org/", }, { name: "NPM", icon: { style: { color: "white", backgroundColor: "#C53635", borderRadius: "50%", padding: "0.05rem", }, svgPath: "fontawesome/npm-brands.svg", }, href: "https://www.npmjs.com/", }, { name: "Ubuntu", icon: { style: { color: "#D74614", backgroundColor: "white", borderRadius: "50%", }, svgPath: "fontawesome/ubuntu-brands.svg", }, href: "https://ubuntu.com/", }, { name: "VSCode", icon: { svgPath: "seek-logo/vscode.svg", }, href: "https://code.visualstudio.com/", }, ] export default tools
angelxehg/angelxehg.github.io
src/meta/data/frameworks.ts
<filename>src/meta/data/frameworks.ts import { LinkMeta } from "../types" const frameworks: LinkMeta[] = [ { name: "Angular", icon: { style: { color: "#D6002F" }, svgPath: "seek-logo/angular.svg", }, href: "https://angular.io/", }, { name: "Bootstrap", icon: { svgPath: "seek-logo/bootstrap.svg", style: { color: "#533B78", }, }, href: "https://getbootstrap.com/docs/", }, { name: "Django", icon: { svgPath: "seek-logo/django.svg", }, href: "https://www.djangoproject.com/", }, { name: "Flutter", icon: { svgPath: "seek-logo/flutter.svg", }, href: "https://flutter.dev/", }, { name: "GatsbyJS", displayName: "Gatsby", icon: { style: { color: "#E94E31", backgroundColor: "white", borderRadius: "50%", }, svgPath: "seek-logo/gatsby.svg", }, href: "https://www.gatsbyjs.com/", }, { name: "Ionic", displayName: "Ionic Framework", icon: { style: { fill: "#4886F1", backgroundColor: "#e6f0ff", borderRadius: "50%", padding: "0.05rem", }, svgPath: "ionicons/ionic.svg", }, href: "https://ionicframework.com/", }, { name: "React", displayName: "React", icon: { style: { color: "#79D8F7", backgroundColor: "#20232a", borderRadius: "50%", padding: "0.05rem", }, svgPath: "fontawesome/react-brands.svg", }, href: "https://es.reactjs.org/", }, { name: "ReactNative", displayName: "React Native", icon: { style: { color: "#79D8F7", backgroundColor: "#20232a", borderRadius: "50%", padding: "0.05rem", }, svgPath: "fontawesome/react-brands.svg", }, href: "https://reactnative.dev/", }, ] export default frameworks
angelxehg/angelxehg.github.io
src/pages/about.tsx
import React from "react" import { CreateLink } from "../components/Link" import Redirect from "../components/Redirect" const UTZACLink = () => ( <a href="http://www.utzac.edu.mx" rel="external" title="UTZAC"> Universidad Tecnológica del Estado de Zacatecas </a> ) export const AboutSection = () => ( <section id="about"> <h2>Acerca de mi:</h2> <div className="row"> <div className="col-12 p-sm-1 pb-3"> <div className="card"> <div className="card-body"> <h3 className="card-title h5">Trayectoria</h3> <p className="card-text m-0"> Mi historia en el mundo de la tecnología comienza en 2014, cuando programé mis primeras aplicaciones, para Windows Phone y Windows. Para lograr esto aprendí Visual Basic, y posteriormente C# y XAML. Realicé algunos proyectos que me ayudaron a entender muchas de las bases de la programación. </p> <p className="card-text m-0 mt-2"> Fue en la Universidad donde comencé a aprender y trabajar con tecnologías web, donde aprendí HTML, Python y JavaScript. También durante este tiempo aprendí por mi cuenta Angular, React y Firebase, y descubrí que lo mio es el desarrollo front-end. </p> <p className="card-text m-0 mt-2"> Desde 2020 he completado proyectos como{" "} <CreateLink from="Web" noIcon extend={{ title: "freelancer en Fiverr", href: "https://www.fiverr.com/angelxehg", }} />{" "} . Ahora acabo de terminar mi carrera en la <UTZACLink />, pero continúo aprendiendo <a href="#skills">nuevas herramientas</a> y creando <a href="#projects">proyectos</a>. </p> </div> </div> </div> <div className="col-md-6 p-sm-1 pb-3"> <div className="card" style={{ height: "100%" }}> <div className="card-body"> <h3 className="card-title h5">Educación</h3> <ul className="p-0 m-0" style={{ listStyleType: "none" }}> <li> Ingeniería en Tecnologías de la Información y Comunicación{" "} <br /> <UTZACLink /> <br /> 2017 - 2021 (En proceso de titulación) </li> </ul> </div> </div> </div> <div className="col-md-6 p-sm-1 pb-3"> <div className="card" style={{ height: "100%" }}> <div className="card-body"> <h3 className="card-title h5">Ubicación</h3> <ul className="p-0 m-0" style={{ listStyleType: "none" }}> <li> <b>Origen</b>: Zacatecas, México </li> <li> <b>Idiomas</b>: Español (nativo), Inglés (intermedio) </li> </ul> </div> </div> </div> </div> </section> ) const AboutPage = (): JSX.Element => <Redirect title="Index" url="/#about" /> export default AboutPage
angelxehg/angelxehg.github.io
src/meta/data/syntax.ts
<filename>src/meta/data/syntax.ts import { LinkMeta } from "../types" const syntaxs: LinkMeta[] = [ { name: "Dart", icon: { svgPath: "seek-logo/dart.svg", }, href: "https://dart.dev/", }, { name: "GraphQL", icon: { svgPath: "seek-logo/graphql.svg", }, href: "https://graphql.org/", }, { name: "HTML5", icon: { style: { color: "#F64A1D" }, svgPath: "seek-logo/html5.svg", }, href: "https://developer.mozilla.org/es/docs/Web/Guide/HTML/HTML5", }, { name: "JavaScript", icon: { style: { color: "#F7DB00", backgroundColor: "black", borderRadius: "15%", }, svgPath: "fontawesome/js-square-brands.svg", }, href: "https://developer.mozilla.org/es/docs/Web/JavaScript", }, { name: "Markdown", icon: { svgPath: "fontawesome/markdown-brands.svg", }, href: "https://www.markdownguide.org/", }, { name: "Python", icon: { svgPath: "seek-logo/python.svg", }, href: "https://www.python.org/", }, { name: "TypeScript", icon: { style: { color: "#356A97" }, svgPath: "seek-logo/typescript.svg", }, href: "https://www.TypeScriptlang.org/", }, ] export default syntaxs
angelxehg/angelxehg.github.io
src/components/Redirect.tsx
<gh_stars>0 import React, { useEffect } from "react" import { navigate } from "gatsby" import CenterLayout from "../layouts/Center" import SEO from "./SEO" interface RedirectProps { title: string url: string } const ConcernedSVG = require("../assets/concerned.svg") const Redirect = (props: RedirectProps): JSX.Element => { useEffect(() => { setTimeout(() => navigate(props.url), 2000) }, []) return ( <CenterLayout> <SEO title="301: Moved Permanently" lang="es" /> <main className="card"> <ConcernedSVG style={{ width: "5rem", height: "5rem" }} className="align-self-center mt-2" /> <div className="card-body"> <h1 className="card-title h5">301: Moved Permanently</h1> <p className="card-text m-0"> Este contenido fue movido a <a href={props.url}>{props.title}</a>. Redireccionando... </p> </div> </main> </CenterLayout> ) } export default Redirect
angelxehg/angelxehg.github.io
src/meta/types.ts
<reponame>angelxehg/angelxehg.github.io import React from "react" export interface IconMeta { // color?: string fill?: boolean style?: React.CSSProperties svgPath: string } export interface LinkMeta { name: string displayName?: string icon: IconMeta href: string }
angelxehg/angelxehg.github.io
src/pages/projects.tsx
import React from "react" import { Link } from "gatsby" import { GatsbyImage } from "gatsby-plugin-image" import Layout from "../layouts/Layout" import DefaultFooter from "../components/Footer" import SEO from "../components/SEO" import { usePages, Page } from "../hooks/use-pages" import DefaultNavbar from "../components/Navbar" import { CreateBadge } from "../components/Link" interface ProjectCardProps { item: Page } const ProjectCard = ( props: ProjectCardProps & { titleAs: "h2" | "h3" } ): JSX.Element => { const { slug, title, image, caption, stack } = props.item return ( <article className="card" style={{ height: "100%" }}> <GatsbyImage image={image} alt={caption} className="card-img-top" /> <div className="card-body"> {props.titleAs === "h2" && ( <h2 className="card-title h5"> <Link to={`/${slug}`}>{title}</Link> </h2> )} {props.titleAs === "h3" && ( <h3 className="card-title h5"> <Link to={`/${slug}`}>{title}</Link> </h3> )} <p className="card-text m-0">{caption}</p> <p className="card-text m-0"> {stack.map(toolName => ( <CreateBadge key={toolName} from={toolName} /> ))} </p> </div> </article> ) } export const ProjectsSection = () => { const projects = usePages().slice(0, 2) return ( <section id="projects"> <h2> Últimos <Link to="/projects">proyectos</Link>: </h2> <div className="row"> {projects.map(item => ( <div key={item.id} className="col-lg-6 p-sm-1 pb-3"> <ProjectCard item={item} titleAs="h3" /> </div> ))} </div> <Link to="/projects">Ver todos los proyectos {">"}</Link> </section> ) } const ProjectsPage = (): JSX.Element => { const projects = usePages() return ( <Layout> <SEO title="Proyectos" lang="es" /> <DefaultNavbar /> <div className="hero"> <div className="container-lg ps-sm-4 pe-sm-4 pt-3 pb-3"> <Link to="/">{"< "}Volver a Portafolio</Link> <header className="mt-1"> <h1>Todos mis proyectos</h1> <p className="m-0">Estos son todos mis proyectos públicos</p> </header> </div> </div> <main className="container-lg ps-sm-4 pe-sm-4 pt-3 pb-3"> <div className="row"> {projects.map(item => ( <div key={item.id} className="col-lg-6 p-sm-1 pb-3"> <ProjectCard titleAs="h2" item={item} /> </div> ))} </div> </main> <DefaultFooter /> </Layout> ) } export default ProjectsPage
angelxehg/angelxehg.github.io
src/components/Icon.tsx
<reponame>angelxehg/angelxehg.github.io<gh_stars>0 import React from "react" import { IconMeta } from "../meta/types" export interface IconProps { size?: string className?: string } const useIconStyle = ( props: IconProps & { meta: IconMeta } ): React.CSSProperties => { const { size } = props return { ...props.meta.style, width: size || "0.9rem", height: size || "0.9rem", } } const Icon = (props: IconProps & { meta: IconMeta }) => { const { svgPath, fill: metaFill } = props.meta const IconSVG = require("../assets/" + svgPath) return ( <IconSVG className={`${metaFill ? "fill-me-anyway" : ""}`} style={useIconStyle(props)} /> ) } export default Icon
angelxehg/angelxehg.github.io
src/components/Header.tsx
<filename>src/components/Header.tsx<gh_stars>0 import React from "react" import "./Header.scss" import { CreateIcon, CreateLink } from "./Link" const email = { from: "Email", title: "Enviame un Email", href: "mailto:<EMAIL>", } const resume = { from: "File", title: "Descarga mi CV", href: "/CV-AngelHurtado-Nov-2021.pdf", } const devTo = { from: "Dev.to", title: "Visita mi blog en dev.to", href: "https://dev.to/angelxehg", } const linkedIn = { from: "LinkedIn", title: "LinkedIn (/in/angelxehg)", href: "https://www.linkedin.com/in/angelxehg", } const gitHub = { from: "GitHub", title: "GitHub (@angelxehg)", href: "https://github.com/angelxehg", } const twitter = { from: "Twitter", title: "Twitter (@angelxehg)", href: "https://www.twitter.com/angelxehg", } const platzi = { from: "Diplomas", title: 'Mis diplomas', href: 'https://platzi.com/p/angelxehg' } const socialLinks = [email, resume, platzi, devTo, linkedIn, gitHub, twitter,] const SocialLinks = () => ( <nav> <p className="d-none d-sm-block"> {socialLinks.map(({ from, title, href }) => ( <CreateIcon key={href} from={from} extend={{ title, href }} iconProps={{ size: "1.5rem" }} /> ))} </p> <ul className="p-0 m-0 d-sm-none" style={{ listStyleType: "none" }}> {socialLinks.map(({ from, title, href }) => ( <li key={href}> <CreateLink from={from} extend={{ title, href }} /> </li> ))} </ul> </nav> ) export const HugeHeader = (): JSX.Element => ( <div className="hero"> <div className="container-lg ps-sm-4 pe-sm-4 huge-header pt-3 pb-3"> <img src="/images/Avataaars.Smile.Sqr.Opt.png" className="rounded-circle fluid align-self-center" alt="<NAME>" style={{ height: "120px", width: "120px", background: "blueviolet" }} /> <header className="mt-2"> <h1><NAME></h1> <p> ¡Hola mundo! Hago web development con <CreateLink from="JavaScript" /> , <CreateLink from="React" /> y <CreateLink from="Angular" /> </p> </header> <SocialLinks /> </div> </div> )
angelxehg/angelxehg.github.io
src/pages/skills.tsx
import React from "react" import stacks from "../meta/stacks" import { CreateBadge } from "../components/Link" import Redirect from "../components/Redirect" const SkillCard = (props: { title: string; tools: string[] }) => ( <div className="card" style={{ height: "100%" }}> <div className="card-body"> <h3 className="card-title h5">{props.title}</h3> <p className="card-text"> {props.tools.map(toolName => ( <CreateBadge key={toolName} from={toolName} /> ))} </p> </div> </div> ) export const SkillsSection = () => ( <section id="skills"> <h2>Habilidades</h2> <div className="row"> {stacks.map(({ title, tools }, n) => ( <div key={n} className="col-lg-6 p-sm-1 pb-3"> <SkillCard title={title} tools={tools} /> </div> ))} </div> </section> ) const SkillsPage = (): JSX.Element => <Redirect title="Skills" url="/#skills" /> export default SkillsPage
angelxehg/angelxehg.github.io
src/meta/links.ts
<reponame>angelxehg/angelxehg.github.io import frameworks from "./data/frameworks" import generics, { genericWebLink } from "./data/generic" import platforms from "./data/platforms" import syntaxs from "./data/syntax" import tools from "./data/tools" import websites from "./data/websites" const allLinks = [ ...generics, ...frameworks, ...syntaxs, ...platforms, ...websites, ...tools, ] export const getLinkMeta = (linkName: string) => { const link = allLinks.find( i => i.name.toLowerCase() === linkName.toLowerCase() ) if (!link) { return genericWebLink } return link } export default allLinks
tawashley/typescript-skill-share
src/3-all-the-types.ts
<filename>src/3-all-the-types.ts /** * 'hello types' * * literal & union types */ type fooString = 'foo'; type onlyFalse = false; const thereIsOnlyOneFoo: fooString = "foo"; const isItStillWarmOutside: onlyFalse = false; type fooObject = { name?: string | string[], string: fooString, hasToBeFalse: onlyFalse } const object: fooObject = { name: '', string: "foo", hasToBeFalse: false } type PersonTitle = 'Mr' | 'Mrs' | 'Miss' | 'Dr' | 'Other' // const title: PersonTitle = /** * enum * * outputs code and used during runtime * * const enum PersonTitleEnum... would prevent this, inlining the value */ enum PersonTitleEnum { Mr, Mrs, Miss, Dr, Other } console.log(PersonTitleEnum.Mr) /** * interfaces * * Work like types but can be merged and extended */ interface PersonDetails { name: string, age?: number, dob: Date, hobbies?: string[] } interface PersonDetails { title: PersonTitle, } const me: PersonDetails = { name: 'Tris', dob: new Date(), age: 0, title: 'Mr' } /** * extending an interface */ interface MorePersonDetails extends PersonDetails { height?: number } // const someoneElse: MorePersonDetails = { // // } /** * function type annotations */ function lengthOfArray(array: []): number { return array.length; } lengthOfArray([]) // lengthOfArray(true) /** * function type alias */ type lengthOfArrayType = (array: []) => number const lengthOfArrayFn: lengthOfArrayType = (array) => { return array.length; } lengthOfArrayFn([]) // lengthOfArrayFn('string') /** * default params * * replace the type with the default value * * The type is inferered from it's value */ function buildName(firstName: string, lastName = "Smith") { return firstName + " " + lastName; } buildName('Foo'); buildName('Foo', 'Bar'); /** * readonly property * * - Compile-time immutability * - Value cannot be set after initialisation */ interface ReadOnlyPerson { readonly name: string, readonly age?: number } const personFrozen: ReadOnlyPerson = { name: 'Person' } // personFrozen.name = ''; // personFrozen.age = 100 /** * generics * * Allows for flexible, 'generic' typing */ type genericTypePassThrough<T> = { (thing: T) : T } const stringPassThrough: genericTypePassThrough<string> = function(thing: string) { return thing; } const boolPassThrough: genericTypePassThrough<boolean> = function(thing: boolean) { return thing; } /** * any type * * remove the type out of TypeScript, * break incase of emergency type, * voids your warrenty, * basically here be dragons... * */ function addTwoNumbersAny(number: any, number2: any): any { return number + number2; } addTwoNumbersAny(1, true); addTwoNumbersAny(NaN, undefined); // function changeReadonlyArrayToAString(array: readonly string[]) { // usage of .pop method dissalowed, as it would be mutating a readonly array function changeReadonlyArrayToAString(array: any) { // any type removes readonly type, we can now do whatever we want with the contents // Array.prototype.pop mutates the array, removing the last element array.pop(); return array; } var array: Readonly<string[]> = ['one', 'two', 'three']; console.log(array); // BEFORE changeReadonlyArrayToAString(array); console.log(array); // AFTER /** * 'as' keyword * * - 'weak-type casting' a type of one thing to another * - none of this touches runtime * - telling the compiler explicity what type it is and what it can be used for * */ // TS knows this will be a form, as we're grabbing a form element var formElement = document.querySelector('form'); // TS doesn't know what type of element it is as we're going off a class var formClassElement = document.querySelector('.payment-form') as HTMLFormElement; // Can also use a generic value var formClassElementGeneric = document.querySelector<HTMLFormElement>('.payment-form'); // compiler still has your back in some aspects though // var obviouslyAString = 'totally-not-an-array'; // // (obviouslyAString as []).join() /** * The 'it's there, honest' operator * * Using '!.' we can tell TS that a nullable value exists no matter what */ const input = document.querySelector('input'); const inputValue = input!.value; /** * function overloading */ // setting the overloaded methods - these are not included in runtime function overloaded(): void; function overloaded(one: string): void; function overloaded(one: string, two: string): void; //implementing overloads with a single method function overloaded(one?: string, two?: string): void { if(one && two) { return console.log('overloaded with two arguments'); } if(one) { return console.log('overloaded with one argument'); } return console.log('no arguments passed, not overloaded'); } overloaded(); overloaded('one arg'); overloaded('one arg', 'two arg'); /** * index types * * - Want to add abit of type safety to dynamic property names * - Super easy way to create hash maps * */ function pluckFromObject<T, K extends keyof T> (dataSet: T, propertyNames: K[]): T[K][] { return propertyNames.map(propertyName => dataSet[propertyName]); } interface Car { manufacturer: string; model: string; year: number; } let taxi: Car = { manufacturer: 'Toyota', model: 'Camry', year: 2014 }; // Manufacturer and model are both of type string, // so we can pluck them both into a typed string array let makeAndModel: string[] = pluckFromObject(taxi, ['manufacturer']); // #Map interface StatusCodeHashMap { [key: number]: string } const httpStatusCodes: StatusCodeHashMap = { 200: "OK", 404: "NOT FOUND", 418: "I'M A TEAPOT" } /** * utility types * * - Built in TS types that take a type as a generic and returns a new type based on it. * - Allows a type to be tweaked without needing to make a seperate type * */ interface BaseInterface { name: string, title: string, age?: number } const allRequiredBase: Required<BaseInterface> = { name: 'name', age: 0, title: 'title' } const allOptional: Partial<BaseInterface> = { name: 'name' } const allReadOnly: Readonly<BaseInterface> = { name: 'name', title: 'title' } // // allReadOnly.age = 20 /** * classes * * compiles to ES6 classes */ interface ClockConstructor { new (hour: number, minute: number): void } interface ClockInterface { hour: number, minute: number, tick(): void } class Clock implements ClockInterface { hour: number; minute: number; constructor(hour: number, minutes: number) { this.hour = hour; this.minute = minutes; } tick() { console.log("beep beep"); } } new Clock(6, 34).tick() /** * side note: limiting the range of a number... * * TypeScript currently doesn't have a 'nice' way of doing this * * but.. * * Can use a number union to limit a value to specific range */ // requires this to be done by hand... // this is only for hours... type TwentyFourHours = 0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23; const clockHour: TwentyFourHours = 17; type NumberZeroToTen = 0|1|2|3|4|5|6|7|8|9|10 const number: NumberZeroToTen = 10;
tawashley/typescript-skill-share
src/4-react.tsx
import React, { Component } from 'react'; interface ComponentProps { prop1: string, prop2: boolean, props3: 'one' | 'two' | 'three' } interface ComponentState { state1: string, state2: boolean } // // 'type up' component props and state // class ReactComponent extends Component<ComponentProps, ComponentState> { state = { state1: 'foo', state2: false } // componentDidMount() { // this.setState({ // // }) // } render() { const { prop1 } = this.props return ( <section> <h1>headding</h1> <p> paragraph </p> </section> ) } } /* <ReactComponent /> */ /* export interface Props { name: string; } // // component with defaultProps // export class Greet extends React.Component<Props> { render() { const { name } = this.props; return <div>Hello ${name.toUpperCase()}!</div>; } static defaultProps = { name: "world"}; } // Type-checks! No type assertions needed! let el = <Greet /> */
tawashley/typescript-skill-share
src/2-with-types.ts
<reponame>tawashley/typescript-skill-share // arbitrary TS example is arbitrary function addTwoNumbers(number1: number, number2: number) { return number1 + number2; } var five = addTwoNumbers(1, 4); // 5, all good // var ten = addTwoNumbers("9", 1); // Compilation error, parameter signiture mismatch // var two = addTwoNumbers(true, true); // same again...
amjha/tseo-assets
app.ts
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; const express = require('express'); const bodyParser = require('body-parser'); const ldap = require('ldapjs'); const jwt = require('jsonwebtoken'); const app = express(); import { resolve } from "path"; import { config } from "dotenv"; config({ path: resolve(__dirname, "../.env") }); import { connectionHandle } from './db'; import { checkAuth } from './checkAuth'; import {Photo} from './model'; const distFolder = '../dist/'; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use((req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader( 'Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept' ); res.setHeader( 'Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS' ); next(); }); app.get('*.*', express.static(distFolder, {maxAge: '1y'})); app.all('/', function(req, res) { res.status(200).sendFile(`/`, {root: distFolder}); }); app.post('/api/login', (req, res) => { const ldapServer = process.env.LDAP; const username = req.body.data.username, password = req.body.data.password; let msgBody; const client = ldap.createClient({ url: `ldap://${ldapServer}` }); client.bind(username, password, function(err) { if (err) { console.log(err.message); msgBody = {code: -1, status: err.message}; } else { const token = jwt.sign({ userId: username}, process.env.JWT_SECRET, {expiresIn: '1h'}); msgBody = {code: 0, status: 'connected', token}; } client.unbind(function(error) { if (error) { console.error(error.message); } }); res.send(msgBody); }); }); app.post('/api/posts', checkAuth, (req, res, next) => { const post = req.body; console.log(post); res.status(201).json({ message: 'Post added successfully' }); }); app.get('/api/photo', checkAuth, async (req, res, next) => { const ontologyRepository = await connectionHandle(); const ontData = await ontologyRepository.find(); res.send(ontData); }); module.exports = app;
amjha/tseo-assets
checkAuth.ts
const jwt = require('jsonwebtoken'); export const checkAuth = (req, res, next) => { try { const token = req.headers.authorization.split(' ')[1]; jwt.verify(token, process.env.JWT_SECRET); next(); } catch (err) { console.log('Authorization failed'); res.status(401).json({message: 'Authorization failed!!'}); } }
amjha/tseo-assets
server.ts
<filename>server.ts const app = require('./app'); const http = require('http'); const normalizePort = val => { const portInt = parseInt(val, 10); if (isNaN(portInt)) { return val; } if (portInt >= 0) { return portInt; } return false; }; const onError = error => { if (error.syscall !== 'listen') { throw error; } const bind = typeof port === 'string' ? 'pipe ' + port : 'port ' + port; switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } }; const onListening = () => { const bind = typeof port === 'string' ? 'pipe ' + port : 'port ' + port; console.log('Listening on ' + bind); }; const port = normalizePort(process.env.PORT || '3000'); const host = process.env.HOST || '0.0.0.0'; app.set('port', port); app.set('host', host); const server = http.createServer(app); server.on('error', onError); server.on('listening', onListening); server.listen(port, host, () => { console.log(`HTTP server listening on host: ${host} and port: ${port}`); });
amjha/tseo-assets
db.ts
import {createConnection} from 'typeorm'; import {Photo} from './model'; let conn; export async function connectionHandle() { if (conn === undefined) { try { // @ts-ignore conn = await createConnection({ type: process.env.DB_TYPE, host: process.env.DB_SERVER, port: process.env.DB_PORT, username: process.env.DB_USER, password: <PASSWORD>, database: process.env.DB_NAME, entities: [ Photo ], synchronize: true, logging: false }); } catch (err) { throw err; } } return conn; }
VitalPointAI/graph-near-blocks
src/mapping.ts
<filename>src/mapping.ts<gh_stars>0 import { near, BigInt } from "@graphprotocol/graph-ts"; import { BlockEvent } from "../generated/schema"; export function handleBlock(block: near.Block): void { const header = block.header; let event = new BlockEvent(header.hash.toHexString()); event.number = BigInt.fromI32(header.height as i32); event.hash = header.hash; //event.timestampNanosec = BigInt.fromU64(header.timestampNanosec); event.gasPrice = header.gasPrice; event.save(); }
abhishekgoenka/training
angular/lab2/my-project/src/app/data-entry/data-entry.component.ts
import { Component, OnInit } from '@angular/core'; import { Post } from '../post'; import { Observable } from 'rxjs'; import { DataService } from '../data.service'; @Component({ selector: 'app-data-entry', templateUrl: './data-entry.component.html', styleUrls: ['./data-entry.component.css'] }) export class DataEntryComponent implements OnInit { isSuccess = false; data: Post = new Post(); constructor(private dataService: DataService) { } ngOnInit() { } onSubmit() { this.dataService.addPost(this.data).subscribe(post => { this.data = post; this.isSuccess = true; }); } }
abhishekgoenka/training
angular/lab2/my-project/src/app/data-entry-reactive/data-entry-reactive.module.ts
<reponame>abhishekgoenka/training<filename>angular/lab2/my-project/src/app/data-entry-reactive/data-entry-reactive.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DataEntryReactiveRoutingModule } from './data-entry-reactive-routing.module'; import { DataEntryReactiveComponent } from './data-entry-reactive.component'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [DataEntryReactiveComponent], imports: [ CommonModule, ReactiveFormsModule, DataEntryReactiveRoutingModule ] }) export class DataEntryReactiveModule { }
abhishekgoenka/training
angular/lab3/my-project/src/app/data-entry/data-entry.component.ts
<gh_stars>1-10 import { Component, OnInit } from '@angular/core'; import { Post } from '../post'; import { Observable } from 'rxjs'; import { DataService } from '../data.service'; import { ActivatedRoute } from '@angular/router'; declare var toastr; @Component({ selector: 'app-data-entry', templateUrl: './data-entry.component.html', styleUrls: ['./data-entry.component.css'] }) export class DataEntryComponent implements OnInit { data: Post = new Post(); editMode = false; constructor(private dataService: DataService, private route: ActivatedRoute) { } ngOnInit() { const id = +this.route.snapshot.paramMap.get('id'); if (id) { this.dataService.postById(id).subscribe((p: Post) => { this.data = p; this.editMode = true; }, () => toastr.error(`Error Occurred`)); } } onSubmit() { if (this.editMode) { this.dataService.updatePost(this.data).subscribe(() => toastr.success(`Record Updated`), () => toastr.error(`Error Occurred`)); } else { this.dataService.addPost(this.data).subscribe(() => toastr.success(`Record saved`), () => toastr.error(`Error Occurred`)); } } }
abhishekgoenka/training
kinetic/Lab/my-project/src/app/toastr.service.ts
import { Injectable } from '@angular/core'; import { EpToastService } from '@epicor/kinetic'; @Injectable({ providedIn: 'root' }) export class ToastrService { constructor(public epToast: EpToastService) {} success(msg: string) { this.toastr(msg, 'success'); } error(msg: string) { this.toastr(msg, 'error'); } private toastr(msg: string, toastType: string) { const tstConfig = { progressBar: true, progressAnimation: 'decreasing', timeOut: 3000, extendedTimeOut: 3000, positionClass: 'toast-top-right', closeButton: true, enableHtml: true }; const toastOpt = { message: `<p><a href="#"><b><u> Click here </u></b></a>${msg}</p>`, title: toastType, toastConfig: tstConfig, toastType: toastType }; this.epToast.show(toastOpt); } }
abhishekgoenka/training
protractor/starter/src/app/app-routing.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { DataEntryComponent } from './data-entry/data-entry.component'; import { ReportComponent } from './report/report.component'; import { DataEntryReactiveComponent } from './data-entry-reactive/data-entry-reactive.component'; const routes = [ { path: '', redirectTo: '/entry', pathMatch: 'full' }, { path: 'entry/:id', component: DataEntryComponent }, { path: 'entry', component: DataEntryComponent }, { path: 'report', component: ReportComponent } ]; @NgModule({ imports: [ RouterModule.forRoot(routes) ], exports: [RouterModule] }) export class AppRoutingModule { }
abhishekgoenka/training
kinetic/Lab/my-project/e2e/src/entry.e2e-spec.ts
<reponame>abhishekgoenka/training import { EntryPage } from './entry.po'; import { browser } from 'protractor'; describe('my-project App', () => { let entry: EntryPage; beforeEach(() => { entry = new EntryPage(); }); it('should be on entry page', () => { entry.getCurrentUrl().then(url => { expect(url).toContain('/entry'); }); }); it('should add new record', () => { entry.setValue('UserId', '1000').then(() => { entry.setValue('title', 'test title').then(() => { entry.setValue('body', 'test body').then(() => { entry.submitButton().click().then(() => { entry.successMsg().getText().then(msg => { browser.sleep(500).then(() => { expect(msg).toBe('Record saved'); }); }); }); }); }); }); }); });
abhishekgoenka/training
protractor/starter/src/app/data.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Post } from './model/post'; import { Observable, throwError, of } from 'rxjs'; import { ApplicationError } from './model/application-error'; import { catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class DataService { private URL = 'http://localhost:3000'; constructor(private http: HttpClient) { } posts(): Observable<Array<Post> | ApplicationError> { return this.http.get<Array<Post>>(`${this.URL}/posts`) .pipe(catchError(error => this.HandleHTTPError(error))); } addPost(newPost: Post): Observable<Post | ApplicationError> { return this.http.post<Post>(`${this.URL}/posts`, newPost) .pipe(catchError(error => this.HandleHTTPError(error))); } postById(id: number): Observable<Post | ApplicationError> { return this.http.get<Post>(`${this.URL}/posts/${id}`) .pipe(catchError(error => this.HandleHTTPError(error))); } deletePost(id: number): Observable<any> { return this.http.delete(`${this.URL}/posts/${id}`) .pipe(catchError(error => this.HandleHTTPError(error))); } updatePost(post: Post): Observable<any> { return this.http.put(`${this.URL}/posts/${post.id}`, post) .pipe(catchError(error => this.HandleHTTPError(error))); } private HandleHTTPError(error: HttpErrorResponse): Observable<ApplicationError> { const appError = new ApplicationError(); appError.errorNumber = 100; appError.errorMsg = error.statusText; return throwError(appError); } }
abhishekgoenka/training
kinetic/Lab/my-project/e2e/src/entry.po.ts
import { browser, by, element, promise } from 'protractor'; export class EntryPage { getCurrentUrl(): promise.Promise<string> { return browser.getCurrentUrl(); } setValue(ele: string, val: string) { return element(by.id(ele)).sendKeys(val); } submitButton() { return element(by.className('btn btn-success')); } successMsg() { return element(by.className('toast toast-success')); } }
abhishekgoenka/training
angular/lab3/my-project/src/app/report/report.component.ts
<reponame>abhishekgoenka/training import { Component, OnInit } from '@angular/core'; import { DataService } from '../data.service'; import { Post } from '../post'; import { Router } from '@angular/router'; declare var toastr; @Component({ selector: 'app-report', templateUrl: './report.component.html', styleUrls: ['./report.component.css'] }) export class ReportComponent implements OnInit { posts: Post[]; constructor(private dataService: DataService, private router: Router) { } ngOnInit() { this.dataService.posts().subscribe((data: Array<Post>) => this.posts = data); } delete(post: Post) { this.dataService.deletePost(post).subscribe(() => toastr.success(`Record deleted`), () => toastr.error(`Error Occurred`)); } edit(post: Post) { this.router.navigate(['entry', post.id]); } }
abhishekgoenka/training
protractor/starter/src/app/data.service.spec.ts
<reponame>abhishekgoenka/training<gh_stars>1-10 import { TestBed, inject } from '@angular/core/testing'; import { DataService } from './data.service'; import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing'; import { Post } from './model/post'; import { ApplicationError } from './model/application-error'; describe('DataService', () => { let httpTestingController: HttpTestingController; let service: DataService; const mockData: Post[] = [ { id: 1, userId: 1, title: 'dummy title 1', body: 'dummy body 1' }, { id: 2, userId: 1, title: 'dummy title 2', body: 'dummy body 2' }, { id: 3, userId: 2, title: 'dummy title 3', body: 'dummy body 3' }, ]; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [DataService] }); httpTestingController = TestBed.get(HttpTestingController); service = TestBed.get(DataService); }); afterEach(() => { // This tests that all HTTP requests have been handled, // and that there are none pending. If there were, then that would also cause the test to fail. httpTestingController.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return all the posts', () => { service.posts().subscribe((posts: Post[]) => { expect(posts.length).toBe(3); }); const postsRequest: TestRequest = httpTestingController.expectOne('http://localhost:3000/posts'); // Back in my code, I'm going to test that the HTTP request made by // GET all posts used the GET HTTP verb. expect(postsRequest.request.method).toBe('GET'); postsRequest.flush(mockData); }); it('should return HTTP Error', () => { service.posts().subscribe(() => fail('this should have been an error'), (error: ApplicationError) => { expect(error.errorNumber).toBe(100); expect(error.errorMsg).toBe('Server Error'); }); const postsRequest: TestRequest = httpTestingController.expectOne('http://localhost:3000/posts'); postsRequest.flush('error', { status: 500, statusText: 'Server Error' }); }); });
abhishekgoenka/training
kinetic/Lab/my-project/e2e/src/app.e2e-spec.ts
import { AppPage } from './app.po'; describe('my-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should have right title', () => { page.navigateTo(); expect(page.getPageTitle()).toEqual('MyProject'); }); });
abhishekgoenka/training
protractor/starter/src/app/data-entry/data-entry.component.edit.spec.ts
<reponame>abhishekgoenka/training<filename>protractor/starter/src/app/data-entry/data-entry.component.edit.spec.ts<gh_stars>1-10 import { TestBed, ComponentFixture } from '@angular/core/testing'; import { DataEntryComponent } from './data-entry.component'; import { DataService } from '../data.service'; import { ActivatedRoute } from '@angular/router'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { Post } from '../model/post'; import { of } from 'rxjs'; describe('DataEntryComponent Edit', () => { let fixture: ComponentFixture<DataEntryComponent>; let component: DataEntryComponent; let mockdataService, mockActivatedRoute; beforeEach(() => { mockdataService = jasmine.createSpyObj(['postById', 'updatePost']); mockActivatedRoute = { snapshot: { paramMap: { get: () => { return 3; }}} }; TestBed.configureTestingModule({ imports: [FormsModule], declarations: [DataEntryComponent], providers: [ {provide: ActivatedRoute, useValue: mockActivatedRoute}, {provide: DataService, useValue: mockdataService} ] }); fixture = TestBed.createComponent(DataEntryComponent); component = fixture.componentInstance; mockdataService.postById.and.returnValue(of<Post>( {id: 1, title: 'dummy title', body: 'dummy body', userId : 1})); mockdataService.updatePost.and.returnValue(of({})); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should be allowed to update record', () => { // To trigger change detection we call the function fixture.detectChanges() fixture.detectChanges(); expect(component.editMode).toBeTruthy(); expect(component.data.id).toBe(1); expect(component.data.title).toBe('dummy title'); expect(mockdataService.postById).toHaveBeenCalledTimes(1); fixture.whenStable().then(() => { const userid = fixture.debugElement.query(By.css('#UserId')); expect(userid.nativeElement.value).toBe('1'); // todo : test for other 2 fields. component.onSubmit(); expect(mockdataService.updatePost).toHaveBeenCalledTimes(1); }); }); });
abhishekgoenka/training
angular/lab3/my-project/src/app/data.service.ts
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { Post } from './post'; @Injectable({ providedIn: 'root' }) export class DataService { private URL = 'http://localhost:3000'; constructor(private http: HttpClient) { } posts(): Observable<Array<Post>> { return this.http.get<Array<Post>>(`${this.URL}/posts`); } postById(id: number): Observable<Post> { return this.http.get<Post>(`${this.URL}/posts/${id}`); } addPost(newPost: Post): Observable<Post> { return this.http.post<Post>(`${this.URL}/posts`, newPost); } deletePost(post: Post): Observable<any> { return this.http.delete(`${this.URL}/posts/${post.id}`); } updatePost(post: Post): Observable<any> { return this.http.put(`${this.URL}/posts/${post.id}`, post); } }
abhishekgoenka/training
kinetic/Lab/my-project/src/app/model/application-error.ts
<filename>kinetic/Lab/my-project/src/app/model/application-error.ts export class ApplicationError { errorNumber: number; errorMsg: string; }
abhishekgoenka/training
angular/lab2/my-project/src/app/report/report.component.ts
import { Component, OnInit } from '@angular/core'; import { DataService } from '../data.service'; import { Post } from '../post'; @Component({ selector: 'app-report', templateUrl: './report.component.html', styleUrls: ['./report.component.css'] }) export class ReportComponent implements OnInit { posts: Post[]; constructor(private dataService: DataService) { } ngOnInit() { this.dataService.posts().subscribe((data: Array<Post>) => this.posts = data); } }
abhishekgoenka/training
protractor/starter/src/app/data-entry-reactive/data-entry-reactive.component.ts
<reponame>abhishekgoenka/training<filename>protractor/starter/src/app/data-entry-reactive/data-entry-reactive.component.ts import { Component, OnInit } from '@angular/core'; import { Post } from '../model/post'; import { DataService } from 'src/app/data.service'; import { FormBuilder, FormControl, Validators, FormGroup } from '@angular/forms'; @Component({ selector: 'app-data-entry-reactive', templateUrl: './data-entry-reactive.component.html', styles: [] }) export class DataEntryReactiveComponent implements OnInit { isSuccess = false; postForm: FormGroup; constructor(private dataService: DataService, private fb: FormBuilder) { this.createForm(); } ngOnInit() { } createForm() { this.postForm = this.fb.group({ userId: new FormControl('', Validators.required), title: new FormControl('', Validators.required), body: new FormControl() }); } onSubmit() { const newPost: Post = this.postForm.value; this.dataService.addPost(newPost).subscribe(post => { if (post) { this.isSuccess = true; } }); } }
abhishekgoenka/training
angular/lab3/my-project/src/app/data-entry/data-entry.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { DataEntryComponent } from './data-entry.component'; import { DataEntryModule } from './data-entry.module'; import { ActivatedRoute } from '@angular/router'; import { DataService } from '../data.service'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; describe('DataEntryComponent', () => { let fixture: ComponentFixture<DataEntryComponent>; let component: DataEntryComponent; let mockdataService, mockActivatedRoute; beforeEach(() => { mockdataService = jasmine.createSpyObj(['']); mockActivatedRoute = { snapshot: { paramMap: { get: () => null}} }; TestBed.configureTestingModule({ imports: [FormsModule], declarations: [DataEntryComponent], providers: [ {provide: ActivatedRoute, useValue: mockActivatedRoute}, {provide: DataService, useValue: mockdataService} ] }); fixture = TestBed.createComponent(DataEntryComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('all the fields should be empty', () => { // To trigger change detection we call the function fixture.detectChanges() fixture.detectChanges(); expect(component.editMode).toBeFalsy(); const userid = fixture.debugElement.query(By.css('#UserId')); expect(userid.nativeElement.textContent).toBe(''); // todo : test for other 2 fields. }); it('should be allowed to add record', () => { fixture.detectChanges(); fixture.whenStable().then(() => { const userid = fixture.debugElement.query(By.css('#UserId')); userid.nativeElement.value = 3; const title = fixture.debugElement.query(By.css('#title')); title.nativeElement.value = 'title testing...'; const body = fixture.debugElement.query(By.css('#body')); body.nativeElement.value = 'body testing...'; expect(userid.nativeElement.value).toBe('3'); // todo : test for other 2 fields. component.onSubmit(); expect(mockdataService.addPost).toHaveBeenCalledTimes(1); }); }); });
yasinskydew/postgres-nest
src/users/users.controllers.ts
import { Body, Controller, Get, Post, Delete, Param } from '@nestjs/common'; import { CreateUserDto } from './users.dto'; import { UsersService} from './users.service'; @Controller('users') export class UsersControllers { constructor(private usersService: UsersService) {} @Post() create(@Body() createUser: CreateUserDto) { return this.usersService.create(createUser); } @Get() findUsers() { return this.usersService.findAll(); } @Get(':id') findUser(@Param('id') id) { return this.usersService.findOne(id); } @Delete(':id') deleteUser(@Param('id') id) { return this.usersService.remove(id); } }
JaviMiot/patternDesignJS_Python
Builder/typeScript/builder.ts
<filename>Builder/typeScript/builder.ts /* ? * Se crea el producto complejo */ class Car { public seats: number = 0; public power: number = 0; public doors: number = 0; public wheels: number = 0; public trunk: boolean = false; public polarizedGlasses: boolean = false; constructor() {} } interface ICarBuilder { addSeats(number: number): void; addPower(number: number): void; addDoor(number: number): void; addWheels(number: number): void; addTrunk(haveTruck: boolean): void; addPolarizedGlasses(havePolarized: boolean): void; getCar(): Car; } class CarBuilder implements ICarBuilder { _instance: Car; constructor() { this._instance = new Car(); } resetCar(): void { this._instance = new Car(); } addSeats(number: number): void { this._instance.seats = number; } addPower(number: number): void { this._instance.power = number; } addDoor(number: number): void { this._instance.doors = number; } addWheels(number: number): void { this._instance.wheels = number; } addTrunk(haveTruck: boolean): void { this._instance.trunk = haveTruck; } addPolarizedGlasses(havePolarized: boolean): void { this._instance.polarizedGlasses = havePolarized; } getCar(): Car { const car = this._instance; this.resetCar(); return car; } } class DirectorCar { carBuilders: ICarBuilder; constructor(builders: CarBuilder) { this.carBuilders = builders; } makeAuto(): void { this.carBuilders.addDoor(4); this.carBuilders.addPower(1.5); this.carBuilders.addSeats(4); this.carBuilders.addTrunk(false); this.carBuilders.addPolarizedGlasses(false); this.carBuilders.addWheels(4); } makeCamion(): void { this.carBuilders.addDoor(2); this.carBuilders.addPower(2.5); this.carBuilders.addSeats(2); this.carBuilders.addTrunk(true); this.carBuilders.addPolarizedGlasses(false); this.carBuilders.addWheels(6); } } const ensambladora = new CarBuilder(); const consecionario = new DirectorCar(ensambladora); consecionario.makeAuto(); const auto = ensambladora.getCar(); consecionario.makeCamion(); const autoCamion = ensambladora.getCar(); console.log(auto); console.log(autoCamion);
JaviMiot/patternDesignJS_Python
State/typeScript/state.ts
<reponame>JaviMiot/patternDesignJS_Python class Bank { private _instanceState!: IStateAccount; private _amount: number = 0; constructor(initialState: IStateAccount) { this.setState(initialState); } public get amount(): number { return this._amount; } public set amount(amount: number) { this.amount = amount; } public setState(state: IStateAccount): void { console.log(`ahora el estado es ${(<any>state).constructor.name}`); this._instanceState = state; this._instanceState.setContext(this); } buy(amount: number) { this._instanceState.buy(amount); } addAmount(amount: number) { this._instanceState.addAmount(amount); } discount(amount: number) { this._amount -= amount; } deposit(amount: number) { this._amount += amount; } } interface IStateAccount { buy(mount: number): void; addAmount(mount: number): void; setContext(context: Bank): void; } class newAccount implements IStateAccount { private _context!: Bank; setContext(context: Bank) { this._context = context; } addAmount(mount: number): void { this._context.deposit(mount); this._context.setState(new NoDeudor()); } buy(mount: number): void { console.log('No tienes dinero, primero has un deposito'); } } class NoDeudor implements IStateAccount { private _context!: Bank; buy(mount: number): void { if (this._context.amount >= mount) { console.log( `tengo en el banco ${this._context.amount} y voy a gastar ${mount}` ); this._context.discount(mount); } else { console.log( `no puedes gastar mas de lo que tienes en el banco ${this._context.amount} y quieres gastar ${mount}` ); } if (this._context.amount == 0) { this._context.setState(new IsDeudor()); } } addAmount(mount: number): void { this._context.deposit(mount); console.log(`ya tienes saldo en tu cuenta :) = ${this._context.amount}`); } setContext(context: Bank): void { this._context = context; } } class IsDeudor implements IStateAccount { private _context!: Bank; buy(mount: number): void { console.log('no tienes saldo suficiente'); } addAmount(mount: number): void { this._context.deposit(mount); console.log(`ya tienes saldo en tu cuenta :) = ${this._context.amount}`); this._context.setState(new NoDeudor()); } setContext(context: Bank): void { this._context = context; } } const bank = new Bank(new newAccount()); bank.buy(19); bank.addAmount(100); bank.buy(10); bank.buy(100); bank.addAmount(200); bank.buy(100); bank.addAmount(100); bank.buy(290); bank.buy(12); bank.addAmount(100); bank.buy(100)
JaviMiot/patternDesignJS_Python
Singleton/typeScript/singleton.ts
<reponame>JaviMiot/patternDesignJS_Python<filename>Singleton/typeScript/singleton.ts<gh_stars>0 class Car { static _instance: Car; color: string; capacity: number; private constructor(color: string, capacity: number) { this.color = color; this.capacity = capacity; } static getInstance(color: string, capacity: number) { if(!this._instance){ this._instance = new Car(color, capacity); } return this._instance; } } const c1 = Car.getInstance('red', 5) const c2 = Car.getInstance('blue', 15) console.log(c1) console.log(c2) console.log(c1==c2)
JaviMiot/patternDesignJS_Python
Factory/typeScript/factory.ts
<reponame>JaviMiot/patternDesignJS_Python /** * ! * Crear una fabrica de Mascotas * */ abstract class PetCreator { abstract createPet(): IPet; } class CreateDog extends PetCreator { ladrido: string; constructor(ladrido: string) { super(); this.ladrido = ladrido; } createPet(): IPet { return new Dog(this.ladrido); } } interface IPet { type: string; age: number; caracteristic: string; walk(): string; jump(): string; eat(): string; } class Dog implements IPet { type: string = ''; age: number = 0; caracteristic: string; constructor(caracteristic: string) { this.caracteristic = caracteristic; } setAge(value: number) { this.age = value; } walk(): string { return `camina y ${this.caracteristic}`; } jump(): string { return `salta y ${this.caracteristic}`; } eat(): string { return `come y ${this.caracteristic}`; } } const dogCreator = new CreateDog('guaaauu gr gr') const dogCreatorBilingual = new CreateDog('guaaauu gr gr helooo!') const dog = dogCreator.createPet() const dogBilingual = dogCreatorBilingual.createPet() console.log(dog.eat()) console.log(dogBilingual.eat())
JaviMiot/patternDesignJS_Python
Strategy/typeScript/strategy.ts
interface IOperation { calculate(number1: number, number2: number): number; } class Sum implements IOperation { calculate(number1: number, number2: number): number { console.log('add'); return number1 + number2; } } class Diff implements IOperation { calculate(number1: number, number2: number): number { console.log('diff'); return number1 - number2; } } class Multi implements IOperation { calculate(number1: number, number2: number): number { console.log('multi'); return number1 * number2; } } class Divide implements IOperation { calculate(number1: number, number2: number): number { console.log('div'); return number1 / number2; } } class MathOperations { private _instance: IOperation; constructor(instance: IOperation) { this._instance = instance; } public set instance(value: IOperation) { this._instance = value; } execute(number1: number, number2: number) { return this._instance.calculate(number1, number2); } } const mathOperations = new MathOperations(new Sum()); console.log(mathOperations.execute(1, 2)); mathOperations.instance = new Diff(); console.log(mathOperations.execute(1, 2)); mathOperations.instance = new Multi(); console.log(mathOperations.execute(4, 2)); mathOperations.instance = new Divide(); console.log(mathOperations.execute(3, 2));
malectro/30songs-gatsby
src/components/page.tsx
import React from 'react'; import {graphql} from 'gatsby'; import Layout from 'src/components/layout.tsx'; import Navigation from 'src/components/navigation.tsx'; import * as css from './page.module.css'; export default function Page({ data, }: { data: { pagesJson: { content: { html: string; }; title: string; description: string; }; }; }) { const { pagesJson: { content: {html}, description, title, }, } = data; return ( <Layout navigation={<Navigation />}> <div className={css.page} dangerouslySetInnerHTML={{__html: html}} /> </Layout> ); } export const query = graphql` query GenericPageQuery($id: String!) { pagesJson(id: {eq: $id}) { id content { html } description title } } `;
malectro/30songs-gatsby
src/components/og-meta.tsx
<filename>src/components/og-meta.tsx import React from 'react'; export const ogMeta = (props: {[key: string]: string}) => ( Object.keys(props).map(key => ( <meta key={key} property={`og:${key}`} content={props[key]} /> )) ); export default ogMeta;
malectro/30songs-gatsby
src/pages/index.tsx
import * as React from 'react'; import Helmet from 'react-helmet'; import {graphql, useStaticQuery, Link} from 'gatsby'; import Layout from 'src/components/layout.tsx'; import socialIcons from 'src/images/social-icons.svg'; import logo from 'src/images/long-logo-1000.svg'; import * as css from './index.module.css'; export default () => { const data: { allSongsJson: { edges: Array<{ node: { id: string; title: string; artist: string; number: number; }, }> }; } = useStaticQuery(query); const header = ( <div className={css.header}> <div className={css.headerQuote}> <div className={css.quote}> “A playlist of songs that <NAME> will hate.” </div> <div> - The Washington Post</div> </div> <div className={css.links}> <Link className={css.linkAbout} to="/about"> About </Link> <a className={css.linkRegister} href="https://www.headcount.org/"> Register to Vote </a> <Link className={css.linkMasthead} to="/masthead"> Masthead </Link> </div> <div className={css.headerSocial}> <a className={css.headerSocialLink} href="https://twitter.com/30days30songs" title="Twitter" > <SocialIcon type="twitter" /> </a> <a className={css.headerSocialLink} href="https://www.facebook.com/30songs30" title="Facebook" > <SocialIcon type="facebook" /> </a> <a className={css.headerSocialLink} href="https://instagram.com/30days30songs" title="Instagram" > <SocialIcon type="instagram" /> </a> <a className={css.headerSocialLink} href="https://www.youtube.com/c/30days30songs" title="Youtube" > <SocialIcon type="youtube" /> </a> </div> </div> ); return ( <Layout header={header} showNavigation={false}> <div className={css.wrapper}> <div className={css.splash}> <img className={css.logo} src={logo} alt="30 Days, 30 Songs" /> <div className={css.social}> <a className={css.socialLink} href="https://open.spotify.com/user/30days30songs/playlist/0GDtTmyBfSvYxMgFCS6yee?utm_campaign=30days30songs&utm_medium=web" paintColor="#efefef" > <SocialIcon type="spotify" /> <span>Listen to the playlist</span> </a> <a className={css.socialLink} href="https://twitter.com/intent/tweet?text=http://www.30days30songs.com" about="_blank" paintColor="#efefef" > <SocialIcon type="twitter" /> <span>Share on Twitter</span> </a> <a className={css.socialLink} href="https://www.facebook.com/sharer/sharer.php?u=http://www.30days30songs.com" paintColor="#efefef" > <SocialIcon type="facebook" /> <span>Share on Facebook</span> </a> </div> <ol className={css.songs}> {data.allSongsJson.edges.map( ({ node: { id, title, artist, number, }, }) => ( <Link className={css.song} to={`/${number}`}> <li className={css.songItem}> <span className={css.songNumber}>{number}</span> <div className={css.songInfo}> <span className={css.songArtist}>{artist}</span> <span className={css.songTitle}>{title}</span> </div> <div className={css.songArrow} /> </li> </Link> ), )} </ol> </div> </div> </Layout> ); }; const query = graphql` query HomePageQuery { allSongsJson( sort: {order: DESC, fields: [number]} filter: {state: {eq: "published"}} ) { edges { node { id artist title number state } } } } `; const SocialIcon = ({type}: {type: string}) => ( <svg className={css.socialIcon}> <use className={css.socialUseIcon} xlinkHref={`${socialIcons}#${type}-icon`} /> </svg> );
malectro/30songs-gatsby
src/components/navigation.tsx
<filename>src/components/navigation.tsx import * as React from 'react'; import classnames from 'classnames'; import {useStaticQuery, graphql, Link} from 'gatsby'; import {StaticImage} from 'gatsby-plugin-image'; import * as css from './navigation.module.css'; export default function Navigation({ songNumber, latestSongNumber = 10, }: { songNumber?: number; latestSongNumber?: number; }) { const data: { allSongsJson: { totalCount: number; }; allNavlinksJson: { nodes: Array<{ url: string; name: string; }>, } } = useStaticQuery(query); if (!data) { return null; } const navLinks = data.allNavlinksJson.nodes; const totalSongs = data.allSongsJson.totalCount; /* const navLinks = nodes .filter(({fileAbsolutePath}) => fileAbsolutePath.match(/\/navLinks\//)) .map(({id, frontmatter}) => ({ ...frontmatter, id, })); */ /* const totalSongs = nodes.filter( ({fileAbsolutePath, frontmatter: {state}}) => state === 'published', ).length; */ return ( <div className={css.fixedSpace}> <div className={css.fixed}> <nav className={css.main}> <div className={css.top} paintColor=""> “A playlist of songs that <NAME> will hate.” <div>The Washington Post</div> </div> <Link className={css.logoLink} to="/"> <StaticImage className={css.logoImg} src="../images/logo-simple-1000.svg" /> </Link> {Number.isInteger(songNumber) ? ( <div className={css.songLinksArrows}> {songNumber > 1 ? ( <Link className={css.arrowLeft} to={`/${songNumber - 1}`} title="Previous Song" /> ) : ( <div className={css.arrowBlank} /> )} <div className={css.arrowNumber}>{songNumber}</div> {songNumber < totalSongs ? ( <Link className={css.arrowRight} to={`/${songNumber + 1}`} title="Next Song" /> ) : ( <div className={css.arrowBlank} /> )} </div> ) : ( <div className={css.songLinksBuffer} /> )} <div className={css.links} paintColor=""> {navLinks.map(navLink => ( <div className={css.link} key={navLink.url}> <Link to={navLink.url}>{navLink.name}</Link> </div> ))} </div> </nav> </div> </div> ); } const query = graphql` query NavigationQuery { allSongsJson(filter: {state: {eq: "published"}}) { totalCount } allNavlinksJson( sort: { fields: [order] } ) { nodes { url name } } } `;
malectro/30songs-gatsby
src/components/layout.tsx
<gh_stars>0 import * as React from 'react'; import Helmet from 'react-helmet'; import {Link} from 'gatsby'; import {StaticImage} from 'gatsby-plugin-image'; import ogMeta from 'src/components/og-meta.tsx'; import * as css from './layout.module.css'; export default function Layout({ header, navigation, children, }: { header?: React.ReactNode; navigation?: React.ReactNode; children: React.ReactNode; }) { const titleText = '30 Days, 30 Songs'; const aboutText = ''; return ( <div className={css.main}> <Helmet> <title>{titleText}</title> {ogMeta({ title: titleText, type: 'website', url: 'http://www.30days30songs.com', image: 'http://www.30days30songs.com/images/logo.png', description: aboutText, site_name: titleText, })} <link href="https://fonts.googleapis.com/css?family=Teko:500" rel="stylesheet" /> <script type="module" src="/js/paint-brush.js" defer async /> </Helmet> {header ? header : <div className={css.empty} />} <div className={css.wrapper}> <div className={css.center}> <div className={css.content}>{children}</div> {navigation} </div> </div> <footer className={css.footer} paintColor="#efefef"> <Link to="/"> <StaticImage className={css.footerEagle} src="../images/eagle.svg" /> </Link> </footer> </div> ); }
malectro/30songs-gatsby
src/components/song.tsx
<gh_stars>0 import * as React from 'react'; import {graphql} from 'gatsby'; import Helmet from 'react-helmet'; import Layout from 'src/components/layout'; import Navigation from 'src/components/navigation'; import ogMeta from 'src/components/og-meta'; import * as css from './song.module.css'; export default function Song({ data, }: { data: { songsJson: { title: string; artist: string; day: number; number: number; youtubeUrl?: string; spotifyUrl?: string; image?: string; gamePath?: string; cropImage: boolean; bio?: string; quote?: string; lyrics?: string; state: 'published' | 'draft' | 'archived'; }; }; }) { const { songsJson: { artist, title, number, day, image, cropImage, youtubeUrl, spotifyUrl, bio, gamePath, lyrics, quote, }, } = data; const youtubeId = youtubeUrl && new URL(youtubeUrl).searchParams.get('v'); return ( <Layout navigation={<Navigation songNumber={number} />}> <Helmet> <title>{artist} - 30 Days, 30 Songs</title> <meta name="description" content={title} /> {ogMeta({ title, type: 'website', url: `http://www.30days30songs.com/${number}`, image: '', description: artist, })} </Helmet> <div className={css.song}> <div className={css.day}> Day {day}, Song {number} </div> <h2 className={css.artist}>{artist}</h2> <h1 className={css.title}>{title}</h1> {youtubeId && ( <iframe className={css.video} src={`https://www.youtube.com/embed/${youtubeId}`} height="340" frameBorder="0" /> )} {spotifyUrl && ( <iframe className={css.widget} src={`https://embed.spotify.com/?uri=${spotifyUrl}`} height="80" frameBorder="0" allowTransparency={true} /> )} <div className={css.info}> <div className={css.infoCol1}> {image?.url && (cropImage ? ( <div className={css.image} style={{backgroundImage: `url(${image.url})`}} /> ) : ( <img className={css.image} src={image.url} /> ))} <div className={css.bio} paintColor="" dangerouslySetInnerHTML={{__html: bio.html}} /> </div> <div className={css.infoCol2}> {gamePath && ( <div> <a className={css.startGame} href="/jets"> <img src="src/images/jets.jpeg" /> </a> </div> )} <div className={css.quote} dangerouslySetInnerHTML={{__html: quote.html}} /> <div className={css.lyricsLabel}>Lyrics</div> <p className={css.lyrics}>{lyrics}</p> </div> </div> </div> </Layout> ); } export const query = graphql` query SongQuery($id: String!) { songsJson(id: {eq: $id}) { id title artist day number youtubeUrl spotifyUrl image { url } cropImage bio { html } quote { html } lyrics state } } `;
dottgonzo/node-file-gen-series
test/main.ts
<gh_stars>0 import * as nodeFileGen from '../index' import * as chai from 'chai' const filepath = '/tmp/Bonobo - Ketto-4tXFA6jTulk.mp4' const filepathZero = '/tmp/Bonobo - Ketto-4tXFA6jTulk_000099.mp4' const options = { numberLenght: 5 } const expect = chai.expect describe('Main File Gen Test', function () { describe('Main File Gen new file', function () { it('generate a file name', function () { const newname = nodeFileGen.genFileSequence(filepath, options) expect(newname).to.be.ok expect(newname).to.be.a('string') }) it('file name contains a number', function () { const newname = nodeFileGen.genFileSequence(filepath, options) console.log(newname) expect(newname.split('_').length).to.be.ok expect(newname.split('_').length).to.be.a('number') expect(newname.split('_')[newname.split('_').length - 1]).to.be.ok expect(newname.split('_')[newname.split('_').length - 1].split('.')[0]).to.be.ok expect(parseInt(newname.split('_')[newname.split('_').length - 1].split('.')[0])).to.be.a('number') expect(newname.split('_')[newname.split('_').length - 1].split('.')[0].length).to.be.eq(options.numberLenght) }) it('file name contains ' + options.numberLenght + ' numbers', function () { const newname = nodeFileGen.genFileSequence(filepath, options) expect(newname.split('_')[newname.split('_').length - 1].split('.')[0].length).to.be.eq(options.numberLenght) }) }) })
dottgonzo/node-file-gen-series
index.ts
import * as fileExists from 'file-exists' import * as fileInfo from 'filenameinfo' import * as fileGen from 'file-gen-series' export interface IFileGenOptions { numberLenght?: number } export interface IFileGenSettings extends IFileGenOptions { numberLenght: number } export function genFileSequence(path: string, options?: IFileGenOptions): string { if (options) { if (!options.numberLenght) options.numberLenght = 5 } else { const settings: IFileGenSettings = { numberLenght: 3 } options = settings } if (!fileExists.sync(fileGen.nextPath(path, options.numberLenght))) { return fileGen.nextPath(path, options.numberLenght) } else { while (fileExists.sync(fileGen.nextPath(path, options.numberLenght))) { path = fileGen.nextPath(fileGen.nextPath(path, options.numberLenght)) } return path } }
rzfury/rentot
index.tsx
import React from "react"; import ReactDOM from "react-dom"; import './src/styles/index.css'; const App = () => { return <p>RnToT</p> } ReactDOM.render(<App/>, document.querySelector("#root"));
Trembit/lite.vatra.com
src/app/stusan/login/login.component.ts
<gh_stars>0 import { Component, OnInit, AfterContentInit, ViewChild, ElementRef, OnDestroy } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { JanusService } from '@shared/services/janus.service'; import { StateService } from '@shared/services/state.service'; import { CreateRoomDto, CreateRoomResponse, RoomExistsDto, RoomExistsResponse } from '@models'; import { SettingsComponent } from '@shared/components/settings/settings.component'; import { SettingsService } from '@shared/services/settings.service'; import { PopupService } from '@shared/services/popup/popup.service'; import { MediaService } from '@shared/services/media.service'; import { CustomizationService } from '../services/customization.service'; import { CustomizationModel } from '../models/customization.model'; import { SoundService } from '@shared/services/sound.service'; @Component({ selector: 'stusan-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], }) export class LoginComponent implements OnInit, OnDestroy, AfterContentInit { destroyed$ = new Subject<boolean>(); @ViewChild('videoPreview') protected videoPreview: ElementRef<HTMLVideoElement>; public loginForm: FormGroup; public microphoneAccess: string; public previewStream: MediaStream | null; public isSirius = false; public customConfig: CustomizationModel; constructor( private fb: FormBuilder, private router: Router, private route: ActivatedRoute, private janusService: JanusService, public stateService: StateService, private soundService: SoundService, private settingsService: SettingsService, private popupService: PopupService, private media: MediaService, public customizationService: CustomizationService, ) { this.stateService.isCamBanned = false; this.media.devicesGetUserMedia(); // check access to cam this.isSirius = customizationService.isSirius(); this.customConfig = customizationService.config; } ngOnInit(): void { const params = new URL(window.location.href).searchParams; if (1 === this.stateService.playLeaveSound ) { // We need to use few values as we have reload on logout this.soundService.playLeave(); this.stateService.playLeaveSound = 0; } else if (2 === this.stateService.playLeaveSound ) { this.stateService.playLeaveSound = 1; } const skip = params.get('skipPrejoin'); const username = params.get('userName'); this.initLoginForm( this.route.snapshot.paramMap.get('roomName') || this.stateService.roomName || '', username || this.stateService.userName || '' ); if (skip) { this.stateService.isCamEnabled = true; this.stateService.isMicEnabled = true; this.onSubmit().then(); } this.settingsService.getDevices().subscribe(({ audioDevices, videoDevices }) => { if (audioDevices?.length && !audioDevices[0].deviceId) { this.microphoneAccess = 'access_denied'; } }); if (!this.stateService.videoEnabled && this.stateService.isCamEnabled) { this.stateService.isCamEnabled = false; // turn of preview } } ngAfterContentInit(): void { this.stateService.isCamEnabled$.pipe(takeUntil(this.destroyed$)).subscribe((isCamEnabled) => { if (isCamEnabled) { this.initVideoPreview(this.stateService.videoDeviceId); } else if (isCamEnabled === null) { this.stateService.isCamEnabled = true; } else { // @here: the place to check for no device enter this.stopVideoPreview(); this.stateService.videoEnabled = false; } }); } public accessMicrophone(): void { // TODO: In Chrome we need to repload page after change permission // from(navigator.mediaDevices.getUserMedia({ audio: true })) // .pipe(takeUntil(this.destroyed$)) // .subscribe(res => { // this.microphoneAccess = ''; // }, err => { // this.microphoneAccess = 'access_denied'; // }); } protected async initVideoPreview(preview: string | null | MediaStream): Promise<void> { if (this.previewStream) { this.stopVideoPreview(); } if (preview instanceof MediaStream) { this.previewStream = preview; this.videoPreview.nativeElement.srcObject = this.previewStream; this.media.saveConstraints(preview); this.microphoneAccess = ''; } else { this.media.getMediaStream(this.stateService.constraints).then((stream) => { this.previewStream = stream; this.videoPreview.nativeElement.srcObject = this.previewStream; this.microphoneAccess = ''; }).catch((error) => { if (error.name === 'ConstraintNotSatisfiedError') { console.error(`Current resolution is not supported by your device.`); } else if (error.name === 'PermissionDeniedError') { console.error('Permissions have not been granted to use your camera and ' + 'microphone, you need to allow the page access to your devices'); } else if ('NotAllowedError' === error.name) { // User blocked cam // console.error(`[loginC] cam is banned `, error); // this.microphoneAccess = 'access_denied'; this.stateService.isCamBanned = true; } else if ('NotFoundError' === error.name) { // user don't have cam this.stateService.isCamBanned = true; } else { console.error(`[loginC] getMediaStream error: ${error.name} :: `, error); } }); } } protected initLoginForm(roomname: string, username = ''): void { this.loginForm = this.fb.group({ roomName: [roomname, [ Validators.required, Validators.minLength(4), Validators.maxLength(50), ]], userName: [username, [ Validators.required, Validators.minLength(4), Validators.maxLength(50), ]], }); this.loginForm.get('userName')?.valueChanges.subscribe((value) => { this.loginForm.get('userName')?.setValue(value.replace(/\s+/g, ' '), { emitEvent: false }); }); } public toggleMic(): void { this.stateService.isMicEnabled = !this.stateService.isMicEnabled; this.stateService.audioEnabled = this.stateService.isMicEnabled; } public toggleCam(): void { this.stateService.isCamEnabled = !this.stateService.isCamEnabled; this.stateService.videoEnabled = this.stateService.isCamEnabled; } public stopVideoPreview(): void { if (this.previewStream) { this.previewStream.getTracks().forEach((track) => { track.enabled = false; }); this.previewStream = null; } } public openSettings(): void { this.popupService.dialog(SettingsComponent, { stream: this.previewStream, closeByEsc: false, panelClass: 'settings-dialog' }, '195px') .afterClosed$.subscribe((result: any) => { if (!!result.data) { this.initVideoPreview(result.data.stream); } }); } public async onSubmit(): Promise<void> { const roomName: string = (this.loginForm.get('roomName') as FormControl).value; const userName: string = (this.loginForm.get('userName') as FormControl).value; let roomId: number; this.stateService.userName = userName; // Check if such room already exists const roomExists: RoomExistsResponse = await this.janusService.roomExists(roomName); if (!(roomExists as RoomExistsDto).exists) { // Room doesn't exists, create new one const createRoomResponse: CreateRoomResponse = await this.janusService.createRoom(roomName); roomId = (createRoomResponse as CreateRoomDto).room; } else { roomId = (roomExists as RoomExistsDto).room; } this.stateService.startTime = Date.now(); this.stateService.isLoggedIn = true; this.stateService.roomId = roomId; if (this.previewStream) { this.media.saveConstraints(this.previewStream); this.stopVideoPreview(); } this.router.navigate(['/', roomName]); } ngOnDestroy() { this.destroyed$.next(true); this.destroyed$.complete(); } }
Trembit/lite.vatra.com
src/app/stusan/shared/services/popup/popup.service.ts
<filename>src/app/stusan/shared/services/popup/popup.service.ts<gh_stars>0 import { ConnectionPositionPair, FlexibleConnectedPositionStrategyOrigin, Overlay } from '@angular/cdk/overlay'; import { ComponentPortal } from '@angular/cdk/portal'; import { ElementRef, Injectable, Injector, TemplateRef, InjectionToken } from '@angular/core'; import { MAT_DIALOG_DATA } from '@angular/material/dialog'; import { PopupComponent } from './popup.component'; import { PopupContent, PopupRef } from './popup.ref'; export const POPUP_DATA = new InjectionToken<{}>('Popup data from parent'); export interface PopupParams<T> { width?: string | number; height?: string | number; panelClass?: string; origin: HTMLElement | ElementRef; content: PopupContent; data?: T; location?: string; } @Injectable({ providedIn: 'root', }) export class PopupService { dropdownPositions: ConnectionPositionPair[] = [ { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', }, ]; menuPositions: ConnectionPositionPair[] = [ { originX: 'center', originY: 'bottom', overlayX: 'center', overlayY: 'top', }, ]; tooltipPositions: ConnectionPositionPair[] = [ { originX: 'end', originY: 'center', overlayX: 'start', overlayY: 'bottom', }, ]; settingsPositions: ConnectionPositionPair[] = [ { originX: 'start', originY: 'top', overlayX: 'end', overlayY: 'bottom', }, ]; constructor( private overlay: Overlay, private injector: Injector, ) { } dropdown<T>(origin: ElementRef, dropdown: TemplateRef<any>, data?: any): PopupRef<T> { const originRect = origin.nativeElement.getBoundingClientRect(); const overlayRef = this.overlay.create({ width: originRect.width, hasBackdrop: true, scrollStrategy: this.overlay.scrollStrategies.reposition(), positionStrategy: this.dropdownPositionStrategy(origin), backdropClass: 'dropdown-backdrop', panelClass: data?.panelClass || 'dropdown-panel', }); const popupRef = new PopupRef<T>(overlayRef, dropdown, data); const injector = Injector.create({ parent: this.injector, providers: [ { provide: PopupRef, useValue: popupRef }, { provide: MAT_DIALOG_DATA, useValue: data }, ], }); overlayRef.attach(new ComponentPortal(PopupComponent, null, injector)); return popupRef; } dropdownPositionStrategy(origin: FlexibleConnectedPositionStrategyOrigin) { return this.overlay.position() .flexibleConnectedTo(origin) .withPositions(this.dropdownPositions) .withFlexibleDimensions() .withViewportMargin(5) .withPush(false); } modal<T>(dialog: any, data?: any, top = '80px'): PopupRef<T> { const overlayRef = this.overlay.create({ hasBackdrop: true, scrollStrategy: this.overlay.scrollStrategies.noop(), positionStrategy: this.overlay.position().global().centerHorizontally().top(top), backdropClass: 'modal-backdrop', panelClass: 'modal-panel', }); const popupRef = new PopupRef<T>(overlayRef, dialog, { ...data, closeByEsc: false }); const injector = Injector.create({ parent: this.injector, providers: [ { provide: PopupRef, useValue: popupRef }, { provide: MAT_DIALOG_DATA, useValue: data }, ], }); overlayRef.attach(new ComponentPortal(PopupComponent, null, injector)); return popupRef; } dialog<T>(dialog: any, data?: any, top = '80px'): PopupRef<T> { const overlayRef = this.overlay.create({ hasBackdrop: true, scrollStrategy: this.overlay.scrollStrategies.block(), positionStrategy: this.overlay.position().global().centerHorizontally().top(top), backdropClass: 'dialog-backdrop', panelClass: ['dialog-panel'].concat(data?.panelClass || []), }); const popupRef = new PopupRef<T>(overlayRef, dialog, data); const injector = Injector.create({ parent: this.injector, providers: [ { provide: PopupRef, useValue: popupRef }, { provide: MAT_DIALOG_DATA, useValue: data }, ], }); overlayRef.attach(new ComponentPortal(PopupComponent, null, injector)); return popupRef; } settings<T>(origin: ElementRef, dialog: any, data?: any): PopupRef<T> { const overlayRef = this.overlay.create({ hasBackdrop: true, scrollStrategy: this.overlay.scrollStrategies.block(), positionStrategy: this.settingsStrategy(origin), backdropClass: 'dialog-backdrop', panelClass: ['dialog-panel'].concat(data?.panelClass || []), }); const popupRef = new PopupRef<T>(overlayRef, dialog, data); const injector = Injector.create({ parent: this.injector, providers: [ { provide: PopupRef, useValue: popupRef }, { provide: MAT_DIALOG_DATA, useValue: data }, ], }); overlayRef.attach(new ComponentPortal(PopupComponent, null, injector)); return popupRef; } settingsStrategy(origin: FlexibleConnectedPositionStrategyOrigin) { return this.overlay.position() .flexibleConnectedTo(origin) .withPositions(this.settingsPositions) .withFlexibleDimensions() .withViewportMargin(5) .withPush(false); } tooltipStrategy(origin: FlexibleConnectedPositionStrategyOrigin) { return this.overlay.position() .flexibleConnectedTo(origin) .withPositions(this.tooltipPositions) .withFlexibleDimensions() .withViewportMargin(5) .withPush(false); } tooltip<T>(origin: ElementRef, tooltip: string | TemplateRef<any>, data: any = null): PopupRef<T> { const overlayRef = this.overlay.create({ hasBackdrop: false, scrollStrategy: this.overlay.scrollStrategies.close(), positionStrategy: this.tooltipStrategy(origin), panelClass: 'tooltip-panel', }); const popupRef = new PopupRef<T>(overlayRef, tooltip, data); const injector = Injector.create({ parent: this.injector, providers: [ { provide: PopupRef, useValue: popupRef }, ], }); overlayRef.attach(new ComponentPortal(PopupComponent, null, injector)); return popupRef; } }
Trembit/lite.vatra.com
src/app/stusan/shared/services/state.service.ts
<reponame>Trembit/lite.vatra.com import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { LayoutType, ThemeType } from '@enums'; import { environment } from '../../../../environments/environment'; import { CustomizationService } from '../../services/customization.service'; @Injectable({ providedIn: 'root', }) export class StateService { get isCamBanned() { // user banned access for cam return (this.getSavedState('isCamBanned') == null) ? false : this.getSavedState('isCamBanned') === 'true'; } set isCamBanned(value: boolean) { this.saveState('isCamBanned', value); } get playLeaveSound() { return this.getSavedState('playLeaveSound') || 0; } set playLeaveSound(value: number) { this.saveState('playLeaveSound', value); } get videoEnabled() { // flag for audioTrack.enabled(paused from docs) return (this.getSavedState('videoEnabled') == null) ? true : this.getSavedState('videoEnabled') === 'true'; } set videoEnabled(value: boolean) { this.saveState('videoEnabled', value); } get audioEnabled() { // flag for audioTrack.enabled(paused from docs) return (this.getSavedState('audioEnabled') == null) ? true : this.getSavedState('audioEnabled') === 'true'; } set audioEnabled(value: boolean) { this.saveState('audioEnabled', value); } get constraints(): any { const saved = this.getSavedState('constraints', 'object') as any; if (saved) { return saved; } return { video: { aspectRatio: 1.77777778, width: 640, height: 360, frameRate: 24 }, audio: { echoCancellation: this.customizationService.config.mediaEchoCancellation, autoGainControl: this.customizationService.config.mediaAutoGainControl, noiseSuppression: this.customizationService.config.mediaNoiseSuppression, } }; } set constraints(constraints: object) { this.saveState('constraints', JSON.stringify(constraints)); } get resolution(): any { const saved = this.getSavedState('resolution', 'object') as any; if (saved) { return saved; } return { width: 'any', height: 'any' }; } set resolution(resolution: object) { this.saveState('resolution', JSON.stringify(resolution)); } roomId$ = new BehaviorSubject<string | number | null>(this.getRoomId() || null); get roomId() { return this.roomId$.getValue(); } set roomId(value: string | number | null) { this.saveState('roomId', value); this.roomId$.next(value); } userName$ = new BehaviorSubject<string | null>(this.getSavedState('userName') || null); get userName() { return this.userName$.getValue(); } set userName(value: string | null) { this.saveState('userName', value); this.userName$.next(value); } roomName$ = new BehaviorSubject<string | null>(this.getSavedState('roomName') || null); get roomName() { return this.roomName$.getValue(); } set roomName(value: string | null) { this.saveState('roomName', value); this.roomName$.next(value); } startTime$ = new BehaviorSubject<number | null>(this.getSavedState('startTime') || null); get startTime() { return this.startTime$.getValue(); } set startTime(value: number | null) { this.saveState('startTime', value); this.startTime$.next(value); } isLoggedIn$ = new BehaviorSubject<boolean | null>(this.getSavedState('isLoggedIn', 'boolean')); get isLoggedIn() { return this.isLoggedIn$.getValue(); } set isLoggedIn(value: boolean | null) { this.saveState('isLoggedIn', value); this.isLoggedIn$.next(value); } isMicEnabled$ = new BehaviorSubject<boolean | null>(this.getSavedState('isMicEnabled', 'boolean') || true); get isMicEnabled() { return this.isMicEnabled$.getValue(); } set isMicEnabled(value: boolean | null) { this.saveState('isMicEnabled', value); this.isMicEnabled$.next(value); } isCamEnabled$ = new BehaviorSubject<boolean | null>(this.getSavedState('isCamEnabled', 'boolean')); get isCamEnabled() { return this.isCamEnabled$.getValue(); } set isCamEnabled(value: boolean | null) { this.saveState('isCamEnabled', value); this.isCamEnabled$.next(value); } get simulcastEnabled(): boolean { return this.getSavedState('simulcast', 'boolean'); } set simulcastEnabled(enabled: boolean) { this.saveState('simulcast', enabled); } theme$ = new BehaviorSubject<ThemeType>(this.getTheme()); get theme() { return this.theme$.getValue(); } set theme(value: ThemeType) { if (value === null) { this.saveState('theme', null); value = ThemeType.Light; } else { this.saveState('theme', value); } this.theme$.next(value); } audioDeviceId$ = new BehaviorSubject<string | null>(this.getSavedState('audioDeviceId') || null); get audioDeviceId() { return this.audioDeviceId$.getValue(); } set audioDeviceId(value: string | null) { this.saveState('audioDeviceId', value); this.audioDeviceId$.next(value); } audioOutputDeviceId$ = new BehaviorSubject<string | null>(this.getSavedState('audioOutputDeviceId') || null); get audioOutputDeviceId() { return this.audioOutputDeviceId$.getValue(); } set audioOutputDeviceId(value: string | null) { this.saveState('audioOutputDeviceId', value); this.audioOutputDeviceId$.next(value); } videoDeviceId$ = new BehaviorSubject<string | null>(this.getSavedState('videoDeviceId') || null); get videoDeviceId() { return this.videoDeviceId$.getValue(); } set videoDeviceId(value: string | null) { this.saveState('videoDeviceId', value); this.videoDeviceId$.next(value); } layoutType$ = new BehaviorSubject<LayoutType>(this.getSavedState('layoutType') || LayoutType.Tile); get layoutType() { return this.layoutType$.getValue(); } set layoutType(value: LayoutType) { this.saveState('layoutType', value); this.layoutType$.next(value); } isChatShown$ = new BehaviorSubject<boolean>(this.getSavedState('isChatShown', 'boolean')); get isChatShown() { return this.isChatShown$.getValue(); } set isChatShown(value: boolean) { this.saveState('isChatShown', value); this.isChatShown$.next(value); } isSettingsShown$ = new BehaviorSubject<boolean>(this.getSavedState('isSettingsShown', 'boolean')); get isSettingsShown() { return this.isSettingsShown$.getValue(); } set isSettingsShown(value: boolean) { this.saveState('isSettingsShown', value); this.isSettingsShown$.next(value); } observedFields = [this.roomId, this.userName, this.roomName, this.startTime, this.isLoggedIn, this.isMicEnabled, this.isCamEnabled, this.theme, this.audioDeviceId, this.audioOutputDeviceId, this.videoDeviceId, this.layoutType, this.isChatShown, this.isSettingsShown]; public isScreenShareEnabled$ = new BehaviorSubject<boolean>(false); constructor(public customizationService: CustomizationService) { // Save values when user refresh page } getRoomId() { const roomIdData = this.getSavedState<string>('roomId'); if (!!roomIdData) { if (environment.janus.stringRoomIds) { return roomIdData; } else { return parseInt(roomIdData, 10); } } else { return null; } } getTheme(): ThemeType { return this.getSavedState('theme') || ThemeType.Light; } getSavedState<T>(key: string, type?: string): T | false { // console.log(`getSavedState ${key}`); try { let saved = localStorage.getItem(key) as unknown; if (!!type) { saved = this.castValueToType(saved, type); } if (saved === 'null') { saved = null; } return saved as T; } catch (e) { console.log('Storage is not available.', this.getAnyClass(e)); if (e instanceof DOMException) { console.log('Using mock responses.'); if (e instanceof DOMException && key === 'roomName') { return ('room123456' as unknown) as T; } else if (e instanceof DOMException && key === 'roomId') { return (2687219796 as unknown) as T; } else if (e instanceof DOMException && key === 'isLoggedIn') { return (true as unknown) as T; } else if (e instanceof DOMException && key === 'userName') { return ('User' as unknown) as T; } } return (null as unknown) as T; } } private getAnyClass(obj: any): string { if (typeof obj === 'undefined') { return 'undefined'; } if (obj === null) { return 'null'; } return obj.constructor.name; } saveState(key: string, value: any): void { try { if (value === null) { localStorage.removeItem(key); } else { localStorage.setItem(key, value.toString()); } } catch (e) { console.log('Storage is not available.', e); } } castValueToType(value: unknown, type: string) { if (type === 'boolean') { if (value === null) { return null; } if (!value) { return false; } if (typeof value === 'string') { return JSON.parse(value); } } if (type === 'object') { if (typeof value === 'string') { try { return JSON.parse(value); } catch (error) { console.log('[State]', error, value); } } } return value; } clearState(): void { this.roomId = null; this.startTime = null; this.isLoggedIn = false; } }
Trembit/lite.vatra.com
src/app/stusan/shared/components/toggle/toggle.component.ts
<gh_stars>0 import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Input } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; @Component({ selector: 'thevatra-toggle', templateUrl: './toggle.component.html', styleUrls: ['./toggle.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: ToggleComponent, }, ], }) export class ToggleComponent implements ControlValueAccessor { value = false; disabled = false; touched = false; get icon(): string | null { if (!!this.iconOn || !!this.iconOff) { return !!this.value ? this.iconOn : this.iconOff; } return null; } @Input('icon-off') iconOff: string; @Input('icon-on') iconOn: string; constructor(private cdr: ChangeDetectorRef) { } onChange = (on: boolean) => { }; onTouched = () => { }; writeValue(value: boolean): void { this.value = value; } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } markAsTouched() { if (!this.touched) { this.onTouched(); this.touched = true; this.cdr.markForCheck(); } } setDisabledState(disabled: boolean) { this.disabled = disabled; this.cdr.markForCheck(); } toggle(): void { if (!this.disabled) { this.value = !this.value; this.onChange(this.value); this.cdr.markForCheck(); } } }
Trembit/lite.vatra.com
src/app/stusan/shared/services/index.ts
<gh_stars>0 export * from './janus.service'; export * from './state.service';
Trembit/lite.vatra.com
src/app/stusan/models/customization.model.ts
<reponame>Trembit/lite.vatra.com export interface CustomizationModel { homeLogo: string; // if null - hide logo roomLogo?: string; homeShowDescription: {}; // true by default, false for grouproom.sirius.video. mediaEchoCancellation: {}; // by default mediaAutoGainControl: {}; // by default mediaNoiseSuppression: {}; // by default favicon: string; title: string; server: string; bitrate?: number; }
Trembit/lite.vatra.com
src/app/stusan/models/janus.dto.ts
<gh_stars>0 import Janus from '../../../assets/stusan/scripts/janus'; import { JanusJS } from '../../../assets/stusan/scripts/janus'; export interface JanusInterface extends Janus { reconnect: (options: JanusJS.ReconnectOptions) => void; }
Trembit/lite.vatra.com
src/app/stusan/enums/index.ts
export * from './layout-type'; export * from './theme-type'; export * from './video-type';
Trembit/lite.vatra.com
src/app/stusan/enums/layout-type.ts
export enum LayoutType { Leader = 'leader', Tile = 'tile', }
Trembit/lite.vatra.com
src/app/app.component.ts
import { Component, Inject, OnInit } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { Title } from '@angular/platform-browser'; import { StateService } from './stusan/shared/services/state.service'; import { ThemeType } from './stusan/enums'; import { CustomizationService } from './stusan/services/customization.service'; @Component({ selector: 'stusan-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit { favIcon: HTMLLinkElement; constructor(@Inject(DOCUMENT) private document: Document, private stateService: StateService, public customizationService: CustomizationService, private title: Title, ) { this.favIcon = this.document.querySelector('#appIcon') as HTMLLinkElement; this.favIcon.href = customizationService.config.favicon; } ngOnInit(): void { this.title.setTitle(this.customizationService.config.title); this.stateService.theme$ .subscribe((theme: ThemeType) => { this.document.documentElement.setAttribute('data-theme', theme); }); } }
Trembit/lite.vatra.com
src/app/stusan/room/header/header.component.ts
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { interval, pipe } from 'rxjs'; import { map, startWith } from 'rxjs/operators'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { JanusService } from '@shared/services/janus.service'; import { StateService } from '@shared/services/state.service'; import { LayoutType } from '@enums'; import { CustomizationModel } from '../../models/customization.model'; import { CustomizationService } from '../../services/customization.service'; @UntilDestroy() @Component({ selector: 'stusan-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class HeaderComponent implements OnInit { public roomName?: string; public isSirius = false; public customConfig: CustomizationModel; constructor( public janusService: JanusService, public stateService: StateService, public customizationService: CustomizationService, private cdr: ChangeDetectorRef, ) { this.isSirius = customizationService.isSirius(); this.customConfig = customizationService.config; } public startTimer$ = interval(1000).pipe( map((seconds: number) => { if (this.stateService.startTime) { return new Date(Date.now() - this.stateService.startTime) .toUTCString() .substring(17, 25); } else { return new Date(); } // In order to get rid of time offset }), startWith('00:00:00'), pipe(untilDestroyed(this)), ); public LayoutTypeEnum = LayoutType; ngOnInit(): void { this.stateService.roomName$.subscribe((name) => { if (name) { this.roomName = name; } this.cdr.markForCheck(); }); } public setLayoutType(layoutType: LayoutType): void { this.stateService.layoutType$.next(layoutType); } }
Trembit/lite.vatra.com
src/app/stusan/room/controls/controls.component.ts
<reponame>Trembit/lite.vatra.com import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild, ElementRef, OnDestroy } from '@angular/core'; import { Router } from '@angular/router'; import * as Sentry from '@sentry/browser'; import { BehaviorSubject, Subject } from 'rxjs'; // @ts-ignore import callstats from 'callstats-js/callstats.min'; import { StateService } from '@shared/services/state.service'; import { JanusService } from '@shared/services/janus.service'; import { PopupService } from '@shared/services/popup/popup.service'; import { SettingsComponent } from '@shared/components/settings/settings.component'; import { MediaService } from '@shared/services/media.service'; import { PopupRef } from '@shared/services/popup/popup.ref'; import { takeUntil } from 'rxjs/operators'; @Component({ selector: 'stusan-controls', templateUrl: './controls.component.html', styleUrls: ['./controls.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ControlsComponent implements OnInit, OnDestroy { destroyed$ = new Subject<boolean>(); @ViewChild('settingsButton', { read: ElementRef }) settingsButton: ElementRef<any>; public roomUrl: string = window.location.href; public isInviteParticipantShown = new BehaviorSubject<boolean>(false); public isInviteParticipantSuccessShown = new BehaviorSubject<boolean>(false); public isInviteParticipantSuccessTimer: ReturnType<typeof setTimeout>; cameraMuting = false; micMuting = false; settings: PopupRef<any> | null; constructor( private router: Router, public stateService: StateService, public janusService: JanusService, private cdr: ChangeDetectorRef, private popupService: PopupService, private media: MediaService, ) { } ngOnInit(): void { this.stateService.isMicEnabled$.pipe(takeUntil(this.destroyed$)).subscribe(() => { this.cdr.markForCheck(); }); this.stateService.isCamEnabled$.pipe(takeUntil(this.destroyed$)).subscribe(() => { this.cdr.markForCheck(); }); this.janusService.mutes.pipe(takeUntil(this.destroyed$)).subscribe((mute) => { if (mute) { if (mute.type === 'video') { this.cameraMuting = false; this.janusService.sendDCVideoMessage(); } else if (mute.type === 'audio') { this.janusService.sendDCMessage(); this.micMuting = false; } this.cdr.markForCheck(); } }); } public async toggleMic(): Promise<void> { if (!this.micMuting) { this.micMuting = true; this.cdr.markForCheck(); this.janusService.sendAudio(!this.stateService.audioEnabled); } } public toggleCam(): void { if (!this.cameraMuting) { this.cameraMuting = true; this.cdr.markForCheck(); this.janusService.sendVideo(!this.stateService.videoEnabled); } } public toggleMirror(): void {} public finishCall(): void { callstats.sendFabricEvent(this.janusService.getVideoRoomPC(), callstats.fabricEvent.fabricTerminated, this.stateService.roomId); Sentry.configureScope(scope => scope.setUser(null)); this.stateService.clearState(); if (this.stateService.playLeaveSound !== -1) { this.stateService.playLeaveSound = 2; // 2 - reload + play, 1 - play + set to zero } this.janusService.finishCall(); this.router.navigate(['/']).then(() => { // TODO: This workaround fix issues after finishing call // In future we need remove this code and handle in proper way the finishing call window.location.reload(); }); } public toogleShareScreen(): void { this.stateService.isScreenShareEnabled$.next(!this.stateService.isScreenShareEnabled$.value); this.janusService.switchShareScreen(this.stateService.isScreenShareEnabled$.value); } public toggleInviteParticipant(): void { if (this.isInviteParticipantShown.value || this.isInviteParticipantSuccessShown.value) { this.isInviteParticipantShown.next(false); } else { this.isInviteParticipantShown.next(true); } this.isInviteParticipantSuccessShown.next(false); clearTimeout(this.isInviteParticipantSuccessTimer); } public copyRoomUrl(): void { navigator.clipboard.writeText(this.roomUrl).then((result) => { this.isInviteParticipantShown.next(false); this.isInviteParticipantSuccessShown.next(true); clearTimeout(this.isInviteParticipantSuccessTimer); this.isInviteParticipantSuccessTimer = setTimeout(() => { this.isInviteParticipantSuccessShown.next(false); }, 3000); }, (error) => { this.isInviteParticipantSuccessShown.next(false); }); } public raiseHand(): void { } public toggleChat(): void { this.stateService.isChatShown$.next(!this.stateService.isChatShown$.value); this.stateService.isSettingsShown$.next(false); } public toggleSettings(): void { if (this.settings) { this.closeSettings(); } else { this.openSettings(); } } private openSettings() { const origin = this.settingsButton.nativeElement; this.settings = this.popupService.settings(origin, SettingsComponent, { stream: this.media.camera, closeByEsc: false }); this.settings.afterClosed$.pipe(takeUntil(this.destroyed$)).subscribe((result: any) => { this.settings = null; if (!!result.data.changed) { if (result.data.stream instanceof MediaStream) { this.media.saveConstraints(result.data.stream); this.janusService.replaceVideo(result.data.stream); } } }); } private closeSettings() { this.settings?.close(); } ngOnDestroy() { this.destroyed$.next(true); this.destroyed$.complete(); } }
Trembit/lite.vatra.com
src/app/stusan/shared/pipes/first-word.pipe.ts
<filename>src/app/stusan/shared/pipes/first-word.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'firstWord' }) export class GetFirstWord implements PipeTransform { transform(value: string): string { value = ('' + value).trim(); if (!value) { return ''; } if (value.indexOf(' ') === -1) { return value[0]; } else { const splitRes = value.split(' '); return splitRes[0][0] + splitRes[1][0]; } } }
Trembit/lite.vatra.com
src/environments/environment.prod.ts
export const environment = { production: true, sentryDSN: 'https://some-sentry-url.com', sentryOrigin: 'localhost:4200', callstats: { appId: 111222333, appSecret: 'some-app-secret' }, envName: 'prod', janus: { debug: false, stringRoomIds: false, server: 'wss://janus-cloud-url.com:443' }, };
Trembit/lite.vatra.com
src/app/app.module.ts
<reponame>Trembit/lite.vatra.com import { ErrorHandler, NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MatDialogModule } from '@angular/material/dialog'; import * as Sentry from '@sentry/angular'; import { OverlayModule } from '@angular/cdk/overlay'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { SharedModule } from './stusan/shared/shared.module'; import { PopupComponent } from './stusan/shared/services/popup/popup.component'; import { CustomizationService } from './stusan/services/customization.service'; import { environment } from 'src/environments/environment'; @NgModule({ declarations: [ AppComponent, PopupComponent, ], imports: [ BrowserModule, AppRoutingModule, MatDialogModule, OverlayModule, SharedModule, ], providers: [ CustomizationService, { provide: ErrorHandler, useValue: Sentry.createErrorHandler({ // @todo: turn On if needed showDialog: false, // environment.production, // turn on only for production }), }, ], bootstrap: [AppComponent], }) export class AppModule { }
Trembit/lite.vatra.com
src/environments/environment.ts
// This file can be replaced during build by using the `fileReplacements` array. // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. // The list of file replacements can be found in `angular.json`. export const environment = { production: false, sentryDSN: 'https://some-sentry-url.com', sentryOrigin: 'localhost:4200', callstats: { appId: 111222333, appSecret: 'some-app-secret', }, envName: 'develop', janus: { debug: false, stringRoomIds: false, server: 'wss://janus-cloud-url.com:443', }, };
Trembit/lite.vatra.com
src/app/stusan/shared/services/popup/popup.ref.ts
import { OverlayRef } from '@angular/cdk/overlay'; import { TemplateRef, Type } from '@angular/core'; import { Subject } from 'rxjs'; export interface PopupCloseEvent<T = any> { type: 'backdropClick' | 'close' | 'escKey'; data: T; } export type PopupContent = TemplateRef<any> | Type<any> | string; export class PopupRef<T = any> { private afterClosed = new Subject<PopupCloseEvent<T>>(); private onKeyDown = new Subject<KeyboardEvent>(); afterClosed$ = this.afterClosed.asObservable(); onKeyDown$ = this.onKeyDown.asObservable(); constructor( public overlay: OverlayRef, public content: PopupContent, public data: any, ) { overlay.backdropClick().subscribe(() => { if (!data || data.closeByClick === true) { this._close('backdropClick'); } }); overlay.keydownEvents().subscribe((event: KeyboardEvent) => { this.onKeyDown.next(event); if (event.code === 'Escape' && (!data || data.closeByEsc !== false)) { this._close('escKey'); } }); } close(data?: any) { this._close('close', data); } private _close(type: PopupCloseEvent['type'], data?: any) { this.overlay.dispose(); this.afterClosed.next({ type, data, }); this.afterClosed.complete(); } }
Trembit/lite.vatra.com
src/app/stusan/models/join-room.dto.ts
<reponame>Trembit/lite.vatra.com import { JanusErrorDto } from './janus-error.dto'; interface Publishers { id: string; // <unique ID of active publisher #1> display?: string; // <display name of active publisher #1, if any> audio_codec: string; // <audio codec used by active publisher #1, if any> video_codec: string; // <video codec used by active publisher #1, if any> simulcast: boolean; // <true if the publisher uses simulcast (VP8 and H.264 only)> talking: boolean; // <true|false, whether the publisher is talking or not (only if audio levels are used)> } interface Attendees { id: string; // <unique ID of attendee #1> display: string; // <display name of attendee #1, if any> } export interface JoinRoomDto { videoroom: 'joined'; room: string; // <room ID> description?: string; // <description of the room, if available> id: string; // <unique ID of the participant> private_id: string; // <a different unique ID associated to the participant; meant to be private> publishers: Publishers[]; // Other active publishers attendees: Attendees[]; // Other attendees, only present when notify_joining is set to TRUE for rooms } export interface Participants { display: string; id: number; publisher: boolean ; talking?: boolean; } export type JoinRoomResponse = JoinRoomDto | JanusErrorDto;
Trembit/lite.vatra.com
src/app/stusan/shared/shared.module.ts
<filename>src/app/stusan/shared/shared.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ScrollingModule } from '@angular/cdk/scrolling'; import { ObserversModule } from '@angular/cdk/observers'; import { PlatformModule } from '@angular/cdk/platform'; import { IconComponent } from './components/icon/icon.component'; import { ControlButtonComponent } from './components/control-button/control-button.component'; import { MicWarningPopupComponent } from './components/mic-warning-popup/mic-warning-popup.component'; import { ToggleComponent } from './components/toggle/toggle.component'; import { DropdownComponent } from './components/dropdown/dropdown.component'; import { VideoComponent } from './components/video/video.component'; import { SettingsComponent } from '@shared/components/settings/settings.component'; import { GetFirstWord } from './pipes/first-word.pipe'; import { SoundService } from './services/sound.service'; const components = [ GetFirstWord, IconComponent, ControlButtonComponent, MicWarningPopupComponent, ToggleComponent, DropdownComponent, VideoComponent, SettingsComponent, ]; @NgModule({ declarations: [ ...components, ], imports: [ CommonModule, FormsModule, ReactiveFormsModule, ScrollingModule, ObserversModule, PlatformModule, ], exports: [ ...components, ScrollingModule, ObserversModule, PlatformModule, ], providers: [ SoundService, ], }) export class SharedModule { }
Trembit/lite.vatra.com
src/app/stusan/room/room.component.ts
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import * as Sentry from '@sentry/browser'; // @ts-ignore import callstats from 'callstats-js/callstats.min'; import { JanusService } from '@shared/services/janus.service'; import { StateService } from '@shared/services/state.service'; import { JoinRoomResponse, RoomExistsDto, RoomExistsResponse } from '@models'; import { environment } from 'src/environments/environment'; @Component({ selector: 'stusan-room', templateUrl: './room.component.html', styleUrls: ['./room.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RoomComponent implements OnInit { isLoggedIn: boolean | null = this.stateService.isLoggedIn; connecting = true; constructor( private router: Router, public stateService: StateService, public janusService: JanusService, private route: ActivatedRoute, private cdr: ChangeDetectorRef, ) { } async ngOnInit(): Promise<void> { this.janusService.connection$.subscribe((connected) => { this.connecting = !connected; this.cdr.markForCheck(); }); const roomName = this.route.snapshot.paramMap.get('roomName'); // TODO: use canLoad if (!this.isLoggedIn) { this.router.navigate(['/login', roomName], { skipLocationChange: true }); return; } let roomId: any = this.stateService.roomId; const userName = this.stateService.userName; // Join room if (userName) { callstats.initialize(environment.callstats.appId, environment.callstats.appSecret, userName); this.janusService.roomInfoSubject.subscribe(({ id }) => { Sentry.setUser({ roomId, userName, roomName, id }); }); if (roomName) { const jsRoomId = this.janusService.roomIdFromName(roomName); if (roomId !== jsRoomId) { // url was corrected roomId = jsRoomId; const roomExists: RoomExistsResponse = await this.janusService.roomExists(roomName); if (!(roomExists as RoomExistsDto).exists) { // Room doesn't exists, create new one await this.janusService.createRoom(roomName); } } } const joinRoomResponse: JoinRoomResponse = await this.janusService.joinRoom(roomId, userName); this.janusService.publishAboutJoin(userName).subscribe(data => { this.stateService.roomName = roomName; this.stateService.roomId = roomId; // TODO: handle case when success published participant }); } } }
Trembit/lite.vatra.com
src/app/stusan/room/videos/videos.component.ts
import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, HostBinding, Input, OnDestroy, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { CdkScrollable } from '@angular/cdk/scrolling'; import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; import { MicState, Video } from '@models'; import { LayoutType, VideoType } from '@enums'; import { JanusService } from '@shared/services/janus.service'; import { StateService } from '@shared/services/state.service'; import { VideoComponent } from '@shared/components/video/video.component'; @Component({ selector: 'stusan-videos', templateUrl: './videos.component.html', styleUrls: ['./videos.component.scss'], changeDetection: ChangeDetectionStrategy.Default, }) export class VideosComponent implements OnInit, AfterViewInit, OnDestroy { destroyed$ = new Subject<boolean>(); public videosArray: Video[]; public videosArrayLength = 0; @Input() set videos(arr: Video[] | null) { this.videosArray = arr || []; if (this.videosArrayLength > this.videosArray.length) { this.setStartEndIndexes(); } this.videosArrayLength = this.videosArray.length; this.pageLimit = Math.ceil(this.videosArrayLength / this.pageSize); this.onSetVideos(this.videosArray); } get videos(): Video[] { return this.videosArray; } @ViewChildren('videoContainer') videoContainers: QueryList<ElementRef>; @ViewChildren('other') otherVideos: QueryList<VideoComponent>; @HostBinding('class') layoutType: LayoutType = LayoutType.Leader; @ViewChild('sourceWrapper', { static: false, read: CdkScrollable }) sourceWrapper: CdkScrollable; public videosOffset = 0; public offsetArray: any[] = []; public VideoTypeEnum = VideoType; public readonly VIDEO_SELFIE = 'data-selfie'; public readonly VIDEO_MAIN = 'data-main'; public readonly VIDEO_PREVIOUS = 'data-previous'; public readonly VIDEO_NEXT = 'data-next'; public leader: Video; public ownVideoId = 0; public othersArray: Video[]; public othersArrayLength = 0; needScroll = true; // false was before isScrollLeft = true; isScrollRight = true; startIndex = 0; endIndex = 2; pageSize = 3; currentPage = 0; pageLimit = 0; tileItemsOnScreen = 6; constructor( public janusService: JanusService, public stateService: StateService ) { // this.test(7); // For testing ///////////////////// } async ngOnInit(): Promise<void> { this.ownVideoId = this.janusService.getLocalUserId(); this.stateService.layoutType$.pipe(takeUntil(this.destroyed$)).subscribe((layoutType: LayoutType) => { this.layoutType = layoutType; this.setStartEndIndexes(); }); this.janusService.camState$.pipe( filter((camState: MicState) => camState.enabled === false), takeUntil(this.destroyed$), ).subscribe((camState: MicState) => { if (this.layoutType === LayoutType.Leader && this.leader.id !== this.ownVideoId && camState.userId === this.leader.id ) { // set the leader to own const ownVideo = this.videosArray.find((source) => source.id === this.ownVideoId); if (!ownVideo) { return; } this.setLeader(ownVideo); } }); } setStartEndIndexes() { if (this.layoutType === LayoutType.Leader) { this.startIndex = 0; this.endIndex = 2; } else { this.startIndex = 0; this.currentPage = 0; this.endIndex = this.tileItemsOnScreen - 1; // the limit is 6 users for Tile Layout // for all visible videos must send video: true this.videosArray.forEach((currentVideo, index) => { if ( index < this.tileItemsOnScreen ) { currentVideo.pluginHandle.send({ message: { request: 'configure', video: true } }); } }); } } onPrevTile() { if (0 <= this.currentPage - 1) { this.currentPage--; this.startIndex = this.currentPage * this.pageSize; } } onNextTile() { if (this.currentPage + 1 < this.pageLimit) { // can be wrong this.currentPage++; this.startIndex = this.currentPage * this.pageSize; } } showPrev() { if (0 <= this.startIndex - 1) { this.startIndex--; this.endIndex--; } } showNext() { if (this.othersArrayLength > this.endIndex + 1) { this.startIndex++; this.endIndex++; } } private onSetVideos(videos: Video[]) { if (this.layoutType === LayoutType.Leader) { const ids = this.videosArray.map((video) => video.id ); if (this.videosArrayLength === 1) { this.leader = videos[0]; } // If No Leader OR Leader is a dead(stopped shared) else if ((!this.leader || ids.indexOf(this.leader.id) === -1) && this.videosArrayLength > 0) { this.leader = videos[0]; } } this.filterOthersFromLeader(); } private filterOthersFromLeader() { this.othersArray = this.videosArray.filter((source) => this.leader && source.id !== this.leader.id); this.othersArrayLength = this.othersArray.length; } setLeader(source: Video) { this.leader = {...source}; this.filterOthersFromLeader(); } othersChanged(event: MutationRecord[]) { // this.setScrollStatus(); } test(quantity = 6) { setTimeout(async () => { const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }); const videos: any[] = []; for (let i = 0; i < quantity; i++) { videos.push({ stream, pluginHandle: null, id: Math.floor(1000 + Math.random() * 9000), name: Math.floor(1000 + Math.random() * 9000), remote: i !== 0, type: 'video', }); } this.janusService.videos$.next(videos); // setTimeout(() => { // console.log('[test] ', this.sourceWrapper); // }) }, 3000); } tilesClasses(tiles: number): string | string[] { if (tiles === 1) { return 'only'; } else if (tiles === 2) { return 'two'; } else if (tiles === 4) { return 'four'; } else if (tiles === 3) { return 'four'; } else if (tiles > 3 && tiles < 8) { return 'three-in-row'; } else if (tiles % 4 === 0 || tiles < 10) { return 'three-in-row'; // return 'four-in-row'; } else if (tiles >= 10) { return 'three-in-row'; // return 'five-in-row'; } return 'three-in-row'; } othersClasses(tiles: number): string { // othersClasses(videosArrayLength) for class="viewport" if (tiles <= 4) { return 'lt-four'; // } else if (tiles === 4) { // return 'four'; } else { return 'gt-four'; } } ngAfterViewInit(): void { // this.setScrollStatus(); } public id(index: number, item: Video): number { return item.id; } noVideo(stream: MediaStream) { return stream.getVideoTracks().length === 0; } noAudio(stream: MediaStream) { return stream.getAudioTracks().length === 0; } onVideoClick(element: HTMLDivElement): void { if (this.layoutType === LayoutType.Leader) { if (element.hasAttribute(this.VIDEO_PREVIOUS)) { this.videosOffset--; } else if (element.hasAttribute(this.VIDEO_NEXT)) { this.videosOffset++; } else { // Reset previous main video this.videoContainers.forEach((video: ElementRef) => { video.nativeElement.removeAttribute(this.VIDEO_MAIN); }); // Set current video as main element.setAttribute(this.VIDEO_MAIN, 'true'); } } } scrollSource(next: boolean) { const distance = Math.ceil(this.sourceWrapper.getElementRef().nativeElement.getBoundingClientRect().width); const to = !!next ? { start: this.sourceWrapper.measureScrollOffset('start') + distance } : { end: this.sourceWrapper.measureScrollOffset('end') + distance }; this.sourceWrapper.scrollTo({ ...to, behavior: 'smooth', }); // this.setScrollStatus(); } setScrollStatus() { if (this.sourceWrapper) { const el = this.sourceWrapper.getElementRef().nativeElement; this.needScroll = el.offsetWidth < el.scrollWidth; this.isScrollLeft = this.sourceWrapper.measureScrollOffset('start') > 0; this.isScrollRight = this.sourceWrapper.measureScrollOffset('end') > 0; } } ngOnDestroy() { this.destroyed$.next(true); this.destroyed$.complete(); } }
Trembit/lite.vatra.com
src/app/stusan/models/video.ts
import { JanusJS } from '../../../assets/stusan/scripts/janus'; import { VideoType } from '@enums'; export interface Video { audioKindAdded?: boolean; videoKindAdded?: boolean; stream: MediaStream; pluginHandle: JanusJS.PluginHandle; id: number; name: string | null; remote: boolean; type: VideoType; mutedMic?: boolean; mutedCam?: boolean; } export interface ConnectionInfoModel extends MediaTrackSettings { videoCodec?: string; bitrate?: string; }
Trembit/lite.vatra.com
src/app/stusan/enums/video-type.ts
export enum VideoType { Video = 'video', Screen = 'screen', }
Trembit/lite.vatra.com
src/app/stusan/models/index.ts
export * from './create-room.dto'; export * from './janus-error.dto'; export * from './join-room.dto'; export * from './room-exists.dto'; export * from './video'; export * from './janus.dto'; export * from './text-message.dto';
Trembit/lite.vatra.com
src/app/stusan/room/chat/chat.component.ts
import { Component, OnInit, ChangeDetectionStrategy, HostBinding } from '@angular/core'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { StateService } from '@shared/services/state.service'; @UntilDestroy() @Component({ selector: 'stusan-chat', templateUrl: './chat.component.html', styleUrls: ['./chat.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ChatComponent implements OnInit { @HostBinding('class.opened') isOpened: boolean; constructor( private stateService: StateService, ) { } ngOnInit(): void { this.stateService.isChatShown$ .pipe(untilDestroyed(this)) .subscribe((isChatShown: boolean) => { this.isOpened = isChatShown; }); } public closeMenu(): void { this.stateService.isChatShown$.next(false); } }
Trembit/lite.vatra.com
src/app/stusan/shared/components/settings/settings.component.ts
import { Component, OnInit, ChangeDetectionStrategy, Inject, ViewChild, ElementRef, AfterViewInit, ChangeDetectorRef, OnDestroy } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { MAT_DIALOG_DATA } from '@angular/material/dialog'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { ThemeType } from '@enums'; import { MediaService, Resolution } from '@shared/services/media.service'; import { PopupRef } from '@shared/services/popup/popup.ref'; import { SettingsService } from '@shared/services/settings.service'; import { StateService } from '@shared/services/state.service'; @Component({ selector: 'thevatra-settings', templateUrl: './settings.component.html', styleUrls: ['./settings.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class SettingsComponent implements OnInit, AfterViewInit, OnDestroy { destroyed$ = new Subject<boolean>(); public stream: MediaStream | null; form: FormGroup; videoInputs: any[] = []; audioInputs: any[] = []; videoResolutions: any[] = []; resolutionFailed = false; resolutionSelectionAvailable = true; @ViewChild('preview') preview: ElementRef<HTMLVideoElement>; get audioInput(): string { return this.form.get('mic')?.value || undefined; } constructor( private dialogRef: PopupRef<SettingsComponent>, @Inject(MAT_DIALOG_DATA) public data: any, private fb: FormBuilder, private settingsService: SettingsService, private stateService: StateService, private media: MediaService, private cdr: ChangeDetectorRef, ) { } async ngAfterViewInit(): Promise<void> { await this.settingsService.updateDevices(); this.stateService.isLoggedIn$.pipe(takeUntil(this.destroyed$)).subscribe((isLoggedIn) => { this.resolutionSelectionAvailable = !isLoggedIn; }); if (this.data.stream) { const previewStream = this.data.stream.clone(); this.data.stream.getTracks().forEach((track: MediaStreamTrack) => track.stop()); await this.setPreview(previewStream); } else { const videoDeviceId = this.stateService.videoDeviceId; this.getVideoPreview(videoDeviceId).then(async (stream) => { if (!videoDeviceId) { await this.settingsService.updateDevices(); } await this.setPreview(stream); }); } } optionsFromDevices(devices: MediaDeviceInfo[]) { return devices.map((device) => { return { label: device.label, value: device.deviceId }; }); } optionsFromResolutions(resolutions: Resolution[]) { return resolutions.map(this.optionFromResolution); } optionFromResolution(resolution: Resolution) { return { label: resolution.name, value: resolution }; } ngOnInit(): void { this.settingsService.getDevices().pipe(takeUntil(this.destroyed$)).subscribe((devices) => { this.videoInputs = this.optionsFromDevices(devices.videoDevices); this.audioInputs = this.optionsFromDevices(devices.audioDevices); this.cdr.markForCheck(); }); this.form = this.fb.group({ theme: [this.stateService.theme === ThemeType.Dark, [Validators.required]], camera: [this.stateService.videoDeviceId, [Validators.required]], resolution: ['', this.resolutionSelectionAvailable ? [Validators.required] : []], simulcast: [this.stateService.simulcastEnabled], mic: [this.stateService.audioDeviceId, [Validators.required]], }); this.form.get('theme')?.valueChanges.pipe(takeUntil(this.destroyed$)).subscribe((isDark) => { this.stateService.theme = isDark ? ThemeType.Dark : ThemeType.Light; this.cdr.markForCheck(); }); this.form.get('camera')?.valueChanges.pipe(takeUntil(this.destroyed$)).subscribe((deviceId) => { this.stateService.videoDeviceId = deviceId; this.resolutionFailed = false; this.updatePreview(deviceId); }); this.form.get('resolution')?.valueChanges.pipe(takeUntil(this.destroyed$)).subscribe((resolution) => { if (this.stream) { this.media.applyResolution(this.stream, resolution).then((success) => { if (success) { this.stateService.resolution = resolution; this.resolutionFailed = false; } else { this.resolutionFailed = true; this.form.get('resolution')?.setValue(this.getCurrentResolution(this.stream), { onlySelf: true, emitModelToViewChange: true, emitEvent: false, emitViewToModelChange: true }); } this.cdr.markForCheck(); }); } }); this.form.get('simulcast')?.valueChanges.pipe(takeUntil(this.destroyed$)).subscribe((enabled) => { this.stateService.simulcastEnabled = enabled; }); this.form.get('mic')?.valueChanges.pipe(takeUntil(this.destroyed$)).subscribe((deviceId) => { this.stateService.audioDeviceId = deviceId; }); this.dialogRef.overlay.backdropClick().pipe(takeUntil(this.destroyed$)).subscribe(() => { this.close(); }); this.dialogRef.overlay.keydownEvents().pipe(takeUntil(this.destroyed$)).subscribe((event: KeyboardEvent) => { if (event.code === 'Escape') { this.close(); } }); } async updatePreview(deviceId: string) { if (this.stream) { this.stopStream(this.stream); } const stream = await this.getVideoPreview(deviceId); await this.updateResolutions(stream); await this.setPreview(stream); } async updateResolutions(stream: MediaStream) { const supported = await this.media.getSupportedResolutions(stream, true); this.videoResolutions = this.optionsFromResolutions(supported); this.cdr.markForCheck(); } async setPreview(stream: MediaStream): Promise<void> { this.preview.nativeElement.srcObject = stream; this.preview.nativeElement.muted = true; this.stream = stream; await this.updateForm(this.stream); return this.preview.nativeElement.play(); } async updateForm(stream: MediaStream): Promise<void> { const data: any = {}; await this.updateResolutions(stream); let resolution: any = this.getCurrentResolution(stream); if (resolution) { resolution = this.optionFromResolution(resolution); if (resolution) { data.resolution = resolution.value; } } const mic: string | null = this.getCurrentAudioId(stream) || null; if (mic) { if (mic === 'default') { const defaultMic = await this.settingsService.getDefaultAudioDevice(); if (defaultMic) { data.mic = defaultMic.deviceId; } } else { data.mic = mic; } } const camera: string | null = this.getCurrentVideoId(stream) || null; if (camera) { if (camera === 'default') { const defaultCam = await this.settingsService.getDefaultVideoDevice(); if (defaultCam) { data.camera = defaultCam.deviceId; } } else { data.camera = camera; } } this.form.patchValue(data, { emitEvent: false }); } getVideoPreview(deviceId?: string | null): Promise<MediaStream> { const constraints = { video: !!deviceId ? { deviceId: { exact: deviceId, }, } : true, audio: !!this.audioInput ? { deviceId: { exact: this.audioInput, }, } : true, }; return this.media.getMediaStream(constraints); } stopStream(stream = this.stream) { if (stream) { stream.getTracks().forEach((track) => { track.stop(); }); stream = null; } } close(): void { this.dialogRef.close({ stream: this.stream?.clone(), changed: this.form.touched }); this.stopStream(); } getCurrentResolution(stream: MediaStream | null): Resolution | null { if (stream) { return this.media.getStreamResolution(stream); } return null; } getCurrentVideoId(stream: MediaStream | null): string | null { if (stream) { return this.media.getStreamVideoId(stream); } return null; } getCurrentAudioId(stream: MediaStream | null): string | null { if (stream) { return this.media.getStreamAudioId(stream); } return null; } ngOnDestroy(): void { this.destroyed$.next(true); this.destroyed$.complete(); } }
Trembit/lite.vatra.com
src/app/stusan/shared/components/video/video.component.ts
import { Component, ChangeDetectionStrategy, Input, AfterViewInit, ViewChild, ElementRef, OnDestroy, OnInit } from '@angular/core'; import { Subject } from 'rxjs'; import { filter, takeUntil } from 'rxjs/operators'; // @ts-ignore import { WebRTCStats } from '@peermetrics/webrtc-stats'; import { Video, MicState, ConnectionInfoModel } from '@models'; import { JanusService, StateService } from '@shared/services'; @Component({ selector: 'thevatra-video', templateUrl: './video.component.html', styleUrls: ['./video.component.scss'], changeDetection: ChangeDetectionStrategy.Default, }) export class VideoComponent implements AfterViewInit, OnDestroy, OnInit { destroyed$ = new Subject<boolean>(); public isSelfVideo = false; public showTech = false; public techData: ConnectionInfoModel = {}; private webrtcStats: WebRTCStats = null; public mutedMic = false; public mutedCam = true; public id = 0; private input: Video; private stream: MediaStream; @ViewChild('video') videoEl: ElementRef<HTMLVideoElement>; get video(): HTMLVideoElement { return this.videoEl.nativeElement; } @Input() layoutName = 'leader'; @Input('source') set source(video: Video) { if (video) { this.id = video.id; // this.mutedMic = !!video.mutedMic; this.mutedCam = !!video.mutedCam; this.input = video; this.setStream(video.stream); } } @Input('isHidden') set isHidden(value: boolean) { if (this.input && this.input.pluginHandle) { if (this.id === this.janusService.getLocalUserId()) { // console.log('[send] STOP sending - owner video'); return; } if (this.id === this.janusService.localScreenShareId) { // console.log('[send] STOP sending - share screen'); return; } this.input.pluginHandle.send({ message: { request: 'configure', video: !value }, success: (res: any) => { // console.log(`[send] (${!value}) success res: `, res); }, error: (res: any) => { // console.log(`[send] (${!value}) success res: `, res); } }); } } get isMine(): boolean { return !this.input?.remote; } get isPlaying(): boolean { return !this.video.paused || false; } get name(): string { return this.input?.name || ''; } constructor(private el: ElementRef, public janusService: JanusService, public stateService: StateService) { } changeStream() { // console.log('this.input.pluginHandle: ', this.input); this.input.pluginHandle.send({ message: { substream: 1, request: 'configure' }}); } ngOnInit() { // Load mic state on Init this.mutedMic = !this.janusService.micStates[this.id]; if (undefined === this.janusService.camStates[this.id] && this.input.type === 'screen') { this.mutedCam = false; } else { this.mutedCam = !this.janusService.camStates[this.id]; } // Subscribe to mic events for future changes this.janusService.micState$.pipe( filter((micState: MicState) => micState.userId === this.id), takeUntil(this.destroyed$), ).subscribe((micState: MicState) => { this.mutedMic = !micState.enabled; if (this.input) { this.input.mutedMic = this.mutedMic; // Save mic state in video Obj } }); this.janusService.camState$.pipe( filter((camState: MicState) => camState.userId === this.id), takeUntil(this.destroyed$), ).subscribe((camState: MicState) => { if (camState.userId === this.janusService.localScreenShareId) { return; } this.mutedCam = !camState.enabled; if (this.input) { this.input.mutedCam = this.mutedCam; // Save mic state in video Obj } // console.log('[Vc] mutedCam: ', this.mutedCam, ' this.id: ', this.id ); }); this.isSelfVideo = this.id === this.janusService.getLocalUserId(); } toggleTechInfo(event: MouseEvent) { this.showTech = !this.showTech; if (this.showTech) { this.getStatsFromWebrtc(); } else { this.webrtcStats.removePeer(this.id); } event.stopPropagation(); } getStatsFromWebrtc() { this.techData = { }; if (this.input.stream && this.input.stream.getVideoTracks() && this.input.stream.getVideoTracks()[0] && this.input.stream.getVideoTracks()[0].getSettings() ) { this.techData = this.input.stream.getVideoTracks()[0].getSettings(); } const inputPc = this.input.pluginHandle.webrtcStuff.pc; this.webrtcStats = new WebRTCStats({ getStatsInterval: 3000 }); if (!this.webrtcStats) { return; } this.webrtcStats.addPeer({ pc: inputPc, peerId: this.id, // any string that helps you identify this peer, // remote: false // optional, override the global remote flag }); this.webrtcStats.on('stats', (ev: any) => { if (ev.data.video.outbound && ev.data.video.outbound[0]?.encoderImplementation) { this.techData.videoCodec = ev.data.video.outbound[0]?.encoderImplementation; } if ((this.input.pluginHandle as any).videoCodec) { this.techData.videoCodec = (this.input.pluginHandle as any).videoCodec; } this.techData.bitrate = this.getStringBitrate(ev.data.video); }); } private getStringBitrate(videInfo: any) { let inbound = '0'; if (videInfo.inbound && videInfo.inbound[0]) { if (videInfo.inbound[0].bitrate) { inbound = (videInfo.inbound[0].bitrate / 1024).toFixed(2) + ' Kbps'; } if (videInfo.inbound[0].frameHeight && videInfo.inbound[0].frameWidth) { this.techData.width = videInfo.inbound[0].frameWidth; this.techData.height = videInfo.inbound[0].frameHeight; } } let outbound = '0'; if (videInfo.outbound && videInfo.outbound.length) { const outStream = videInfo.outbound.find((streamOut: any) => streamOut.bitrate); if (outStream) { outbound = (outStream.bitrate / 1024).toFixed(2) + ' Kbps'; } } // console.log(this.id + ' out: ', videInfo.outbound); // console.log(this.id + ' in: ', videInfo.inbound); // [' + videInfo.outbound.length + '] - for simulcast return ' in: ' + inbound + ', out: ' + outbound + '[' + videInfo.outbound.length + ']'; } setStream(stream: MediaStream) { this.stream = stream; if (!this.isMine) { if (!!stream) { stream.onremovetrack = (event) => { console.log('onremovetrack error: ', event); }; stream.onaddtrack = (event) => { console.log('onAddTrack error: ', event); }; } this.stream.addEventListener('addtrack', (event) => { console.log('add', event); }); this.stream.addEventListener('removetrack', (event) => { console.log('remove', event); }); } if (this.videoEl) { this.playVideo(); } } playVideo() { this.video.srcObject = this.stream; this.video.muted = this.isMine; // let promise = this.video.play(); setTimeout(() => { const promise = this.video.play() .then(() => { // console.log('[playVideo] play'); }).catch((error) => { console.error('[playVideo] err: ', error); }); if (promise !== undefined) { promise.catch(error => { // Auto-play was prevented // Show a UI element to let the user manually start playback console.error('[playVideo+promise] err: ', error); }).then(() => { // Auto-play started // console.info('[playVideo+promise] Started ... '); }); } }, 50); } ngAfterViewInit(): void { if (!this.isPlaying) { this.playVideo(); } } fullScreen() { this.el.nativeElement.requestFullscreen().then(() => { console.log('[fullScreen] ok'); }); } ngOnDestroy() { if (this.webrtcStats) { this.webrtcStats.removePeer(this.id); } this.destroyed$.next(true); this.destroyed$.complete(); } }
Trembit/lite.vatra.com
src/app/stusan/shared/components/dropdown/dropdown.component.ts
<reponame>Trembit/lite.vatra.com import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Input, ViewChild, ElementRef, TemplateRef, HostBinding } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { PopupRef } from '@shared/services/popup/popup.ref'; import { PopupService } from '@shared/services/popup/popup.service'; @Component({ selector: 'thevatra-dropdown', templateUrl: './dropdown.component.html', styleUrls: ['./dropdown.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, providers: [ { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: DropdownComponent, }, ], }) export class DropdownComponent implements ControlValueAccessor { value: any; touched = false; opened = false; popup: PopupRef | null; filteredOptions: any[] = []; optionsArray: any[] = []; @HostBinding('class.disabled') disabled = false; @Input() set options(opts: { label: string, value: any }[]) { this.optionsArray = opts; if (Array.isArray(opts)) { this.setDisabledState(opts.length < 2); } else { this.setDisabledState(true); } // this.filteredOptions = opts.filter(option => option.value !== this.value); } get options() { return this.optionsArray.filter(option => option.value !== this.value); } @Input() placeholder: string; @ViewChild('origin') origin: ElementRef<any>; @ViewChild('dropdown') dropdown: TemplateRef<any>; get textValue(): string { const selected = this.optionsArray.find((option) => option.value === this.value); if (selected) { return selected.label; } else { return this.placeholder || 'Select'; } } constructor(private cdr: ChangeDetectorRef, private popupService: PopupService) { } onChange = (on: boolean) => { }; onTouched = () => { }; writeValue(value: boolean): void { this.value = value; this.cdr.markForCheck(); } registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouched = fn; } markAsTouched() { if (!this.touched) { this.onTouched(); this.touched = true; this.cdr.markForCheck(); } } setDisabledState(disabled: boolean) { this.disabled = disabled; this.cdr.markForCheck(); } toggle(): void { if (!this.disabled) { this.opened ? this.close() : this.open(); } } open(): void { this.popup = this.popupService.dropdown(this.origin, this.dropdown); this.opened = true; this.popup.afterClosed$.subscribe((result) => { this.popup = null; this.opened = false; this.cdr.markForCheck(); }); this.cdr.markForCheck(); } close(): void { if (this.popup) { this.popup.close(); } } select(value: any): void { this.markAsTouched(); this.value = value; this.onChange(this.value); this.close(); } }
Trembit/lite.vatra.com
src/app/stusan/models/room-exists.dto.ts
import { JanusErrorDto } from './janus-error.dto'; export interface RoomExistsDto { videoroom: 'success'; room: number; // <unique numeric ID> exists: boolean; } export type RoomExistsResponse = RoomExistsDto | JanusErrorDto;
Trembit/lite.vatra.com
src/app/stusan/shared/services/popup/popup.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { PopupContent, PopupRef } from './popup.ref'; @Component({ templateUrl: './popup.component.html', }) export class PopupComponent implements OnInit { renderMethod: 'text' | 'template' | 'component' = 'component'; content: any; context: any; @ViewChild('template', { static: false }) template: any; constructor(private popupRef: PopupRef) { } ngOnInit() { this.content = this.popupRef.content; if (this.content instanceof TemplateRef) { this.renderMethod = 'template'; const data = this.popupRef.data; this.context = { close: this.popupRef.close.bind(this.popupRef), data, }; } else if (typeof (this.content) === 'string') { this.renderMethod = 'text'; this.context = { close: this.popupRef.close.bind(this.popupRef), }; } } }
Trembit/lite.vatra.com
src/app/stusan/shared/components/mic-warning-popup/mic-warning-popup.component.ts
import {Component, OnInit, ChangeDetectionStrategy, Output, EventEmitter} from '@angular/core'; @Component({ selector: 'thevatra-mic-warning-popup', templateUrl: './mic-warning-popup.component.html', styleUrls: ['./mic-warning-popup.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class MicWarningPopupComponent implements OnInit { @Output() accessMicrophone = new EventEmitter(); constructor() { } ngOnInit(): void { } }
Trembit/lite.vatra.com
src/app/stusan/shared/services/sound.service.ts
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class SoundService { private joinAudio: HTMLAudioElement; private leaveAudio: HTMLAudioElement; constructor() { } public playJoin() { if (!this.joinAudio) { this.joinAudio = new Audio('../../../../assets/media/join.mp3'); } // this.joinAudio.play(); } public playLeave() { if (!this.leaveAudio) { this.leaveAudio = new Audio('../../../../assets/media/leave.mp3'); } // this.leaveAudio.play(); } }
Trembit/lite.vatra.com
src/app/stusan/shared/services/janus.service.ts
import { Injectable } from '@angular/core'; import { Platform } from '@angular/cdk/platform'; // @ts-ignore import callstats from 'callstats-js/callstats.min'; import { BehaviorSubject, Subject, Observable, Observer } from 'rxjs'; import Janus, { JanusJS } from '../../../../assets/stusan/scripts/janus/janus'; import adapter from 'webrtc-adapter'; import { Md5 } from 'md5-typescript'; import { StateService } from './state.service'; import { environment } from '../../../../environments/environment'; import { CreateRoomDto, CreateRoomResponse, JanusErrorDto, JoinRoomDto, JoinRoomResponse, RoomExistsDto, RoomExistsResponse, Video, Participants, JanusInterface, } from '@models'; import { VideoType } from '@enums'; import { MediaService } from './media.service'; import { MessageData, MicState, MicStates } from '../../models/text-message.dto'; import { SoundService } from './sound.service'; import { CustomizationService } from '../../services/customization.service'; @Injectable({ providedIn: 'root', }) export class JanusService { public userIds: number[] = []; public simulcast = false; private reconnectAttempts = 0; protected janus: any; // @ref: JanusInterface protected videoRoomPlugin: any; // @ref: JanusJS.PluginHandle protected videoRoomScreenSharePlugin: any; // @ref: JanusJS.PluginHandle; public dc: RTCDataChannel; private initPromise: Promise<void>; private createSessionPromise: Promise<void>; private attachVideoRoomPluginPromise: Promise<void>; private localUserId: number; public localScreenShareId: number; public roomInfoSubject = new Subject<JoinRoomDto>(); public connection$ = new BehaviorSubject<boolean>(false); public micState$ = new BehaviorSubject<MicState>({ userId: 0, enabled: true }); public micStates: MicStates = {}; // object of states { userId: true|false} public firstMessageSent = false; public camState$ = new BehaviorSubject<MicState>({ userId: 0, enabled: true }); public camStates: MicStates = {}; // object of states { userId: true|false} public localStream$ = new BehaviorSubject<MediaStream | null>(null); private videosArray: Video[] = []; get videos(): Video[] { return this.videosArray; } set videos(videos: Video[]) { this.videosArray = videos; this.videos$.next(videos); } public videos$ = new BehaviorSubject<Video[]>([]); mutes = new BehaviorSubject<{ type: 'audio' | 'video', on: boolean } | null>(null); constructor( private stateService: StateService, private customizationService: CustomizationService, private soundService: SoundService, private media: MediaService, private platform: Platform, ) { this.localUserId = this.getRandomId(); this.mutes.subscribe((mute) => { if (mute) { if (mute.type === 'video') { this.stateService.isCamEnabled = mute.on; } if (mute.type === 'audio') { this.stateService.isMicEnabled = mute.on; } } }); } public getLocalUserId() { return this.localUserId; } // TODO: Use 1 peer connection for all users!!!!! https://janus.conf.meetecho.com/mvideoroomtest.html private init(): Promise<void> { if (!this.initPromise) { this.initPromise = new Promise((resolve, reject) => { Janus.init({ dependencies: Janus.useDefaultDependencies({ adapter }), callback: () => { resolve(); }, }); }); } return this.initPromise; } private async createSession(): Promise<void> { await this.init(); if (!Janus.isWebrtcSupported()) { throw new Error('No WebRTC support'); } if (!this.createSessionPromise) { this.createSessionPromise = new Promise((resolve, reject) => { this.janus = new Janus( { server: this.customizationService.config.server, success: () => { // The session was successfully created and is ready to be used resolve(); }, error: (error) => { // The session was NOT successfully created console.error('[session] Can\'t create session: ', error, ' sessionId: ', this.janus.getSessionId()); reject(error); }, destroyed: () => { // The session was destroyed and can't be used any more. // TODO: redirect to login page }, }); }); } return this.createSessionPromise; } public reconnectSession(): void { if (this.reconnectAttempts++ > 5) { this.stateService.clearState(); this.finishCall(); window.location.reload(); // @dev: this is eq to logout return; } setTimeout(() => { if (this.janus?.reconnect) { this.janus.reconnect({ success: () => { this.reconnectAttempts = 0; console.log('Session successfully reclaimed:', this.janus.getSessionId()); this.soundService.playJoin(); this.stateService.playLeaveSound = 0; }, error: (error: any) => { console.error('[Session] Failed to reconnect[' + this.reconnectAttempts + '] error: ', error); if (error.indexOf('No such session') !== -1) { console.log('[Js] recconect with create new session '); location.reload(); } this.reconnectSession(); }, }); } }, 2000); } private async attachVideoRoomPlugin(): Promise<void> { await this.createSession(); if (!this.attachVideoRoomPluginPromise) { this.attachVideoRoomPluginPromise = new Promise((resolve, reject) => { // Video room https://janus.conf.meetecho.com/videoroomtest.js this.janus.attach( { plugin: 'janus.plugin.videoroom', success: (pluginHandle: any ) => { // JanusJS.PluginHandle this.videoRoomPlugin = pluginHandle; resolve(); }, error: (error: string) => { console.error('Can\'t attach video room plugin to Janus', error); reject(error); }, consentDialog: (on: boolean) => { // We can show here popup, explaining user what he should allow audio & video in the browser }, iceState: (state: string) => { if (state === 'disconnected') { this.soundService.playLeave(); this.stateService.playLeaveSound = -1; // mark for login page to not play Leave sound this.reconnectSession(); } console.log('[P] ICE state changed to ' + state); }, mediaState: (medium: 'audio' | 'video', on: boolean) => { this.mutes.next({ type: medium, on }); // console.log('[P] Janus ' + (on ? 'started' : 'stopped') + ' receiving our ' + medium); }, webrtcState: (on: boolean) => { this.connection$.next(on); if (on) { this.createCsFabric(); this.configureDataChannel(); } }, ondataopen: (data: string) => { // console.log('[P] The DataChannel is available! data: ', data); }, ondata: (data: any) => { // console.log('[P] data: ', data); }, onmessage: (msg: any, jsep: any) => { // TODO: anys const event = msg.videoroom; // console.log('[P] msg: ', msg); if (event) { if (event === 'joined') { if (msg.id) { const existedUserId = this.userIds.find((userId) => userId !== msg.id); if (!existedUserId) { this.userIds.push(msg.id); } } this.roomInfoSubject.next(msg); // Publisher/manager created, negotiate WebRTC and attach to existing feeds, if any // User might change setting on login screen, use them const settings: any = {}; // TODO: any if (this.stateService.audioDeviceId$.value) { settings.audioDeviceId = this.stateService.audioDeviceId$.value; } if (this.stateService.videoDeviceId$.value) { settings.videoDeviceId = this.stateService.videoDeviceId$.value; } this.createOffer(settings); this.soundService.playJoin(); // You Entered the room // Any new feed to attach to const publishers = msg.publishers; if (publishers) { // console.log('!!! new publishers 1 !!!', publishers); this.addPublishers(publishers); } } else if (event === 'destroyed') { // The room has been destroyed } else if (event === 'event') { // Any new feed to attach to? const publishers = msg.publishers; if (publishers) { // @todo: try to avoid setTimeout usage setTimeout(() => { this.sendDCMessage(); // message to DC about mic state as we have new users this.sendDCVideoMessage(publishers[0].id); }, 1000); // console.log('!!! new publishers 2 !!!', publishers); this.soundService.playJoin(); this.addPublishers(publishers); } else if (msg.leaving || msg.unpublished) { // One of the publishers has gone away if (msg.unpublished && msg.unpublished === 'ok') { // That's us this.videoRoomPlugin.hangup(); return; } const leftParticipantId = msg.leaving || msg.unpublished; const leftParticipant = this.videos.find((video: Video) => video.id === leftParticipantId); if (leftParticipant) { leftParticipant.pluginHandle.detach(null); this.videos = this.videos.filter((video: Video) => video.id !== leftParticipantId); this.soundService.playLeave(); // Somebody leaves } if (msg.leaving) { this.userIds = this.userIds.filter((id) => id !== msg.leaving); } } else if (msg.error) { const errorCodesMap: { [key: number]: string; } = {}; errorCodesMap[426] = 'This is a no such room'; const errorHumanDescription = errorCodesMap[msg.error_code] || 'Janus error'; const errorMessage = `Error code:${msg.error_code}. ${errorHumanDescription}. ${msg.error}`; if (434 === msg.error_code || 425 === msg.error_code) { // console.info(`[info] ${msg.error}`); } else { console.error('[event] Error', errorMessage); // alert(errorMessage); } } } } if (jsep) { // Without this video will be lost in 10 seconds this.videoRoomPlugin.handleRemoteJsep({ jsep }); // Check if any of the media we wanted to publish has been rejected (e.g., wrong or unsupported codec) } }, onlocaltrack: (mediaStreamTrack: MediaStreamTrack) => { let videoStream = this.localStream$.value; // : MediaStream if (!videoStream) { videoStream = new MediaStream(); } videoStream.addTrack(mediaStreamTrack); this.localStream$.next(videoStream); this.videos = this.videos.filter((video: Video) => video.remote !== false || video.type === 'screen'); this.videos = [...this.videos, { stream: videoStream, pluginHandle: this.videoRoomPlugin, id: this.localUserId, name: this.stateService.userName, remote: false, type: VideoType.Video, }]; }, onlocalstream: (stream: MediaStream) => { // We have a local stream to display this.localStream$.next(stream); // If we will change audio or video settings, new local stream will be added, // so each time remove previous local streams this.videos = this.videos.filter((video: Video) => video.remote !== false || video.type === 'screen'); this.videos = [...this.videos, { stream, pluginHandle: this.videoRoomPlugin, id: this.localUserId, name: this.stateService.userName, remote: false, type: VideoType.Video, }]; }, onremotestream: (stream: MediaStream) => { }, oncleanup: () => { // PeerConnection with the plugin closed, clean the UI. The plugin handle is still valid so we can create a new one this.localStream$.next(null); }, detached: () => { // console.log('Connection with the plugin closed, get rid of its features. The plugin handle is not valid anymore'); }, }); }); } return this.attachVideoRoomPluginPromise; } // Send local state of mic in DataChannel sendDCMessage() { const micEnabled = this.stateService.audioEnabled; this.micStates[this.localUserId] = !!micEnabled; const message = { feed: this.localUserId, type: 'audio', enabled: micEnabled }; if (this.dc && this.dc.readyState === 'open') { this.dc.send(JSON.stringify(message)); // console.log('[dc] SEND message: ', message); } else { console.error('[DC] can\'t sendDCMessage current state: ', this.dc?.readyState); } this.micState$.next({ userId: this.localUserId, enabled: !!micEnabled}); // Warn Brother (local Video) } sendDCVideoMessage(videoId = 0) { let messageVideoId = this.localUserId; let videoEnabled = this.stateService.videoEnabled; if (videoId && videoId === this.localScreenShareId) { messageVideoId = videoId; videoEnabled = true; // screehShare Video ON } this.camStates[messageVideoId] = !!videoEnabled; const message = { feed: messageVideoId, type: 'video', enabled: videoEnabled }; this.dcSend(message); this.camState$.next({ userId: messageVideoId, enabled: !!videoEnabled}); // Warn Brother (local Video) } private dcSend(message: any) { if (this.dc && this.dc.readyState === 'open') { this.dc.send(JSON.stringify(message)); // console.log('[dc] SEND Video message: ', message, ' this.localScreenShareId: ', this.localScreenShareId); } else { console.error('[DC] can\'t sendDCVideoMessage current state: ', this.dc?.readyState); } } configureDataChannel() { // dc: RTCDataChannel const pc = this.videoRoomPlugin.webrtcStuff.pc; this.dc = (this.videoRoomPlugin.webrtcStuff.dataChannel as any).JanusDataChannel; if (!this.dc) { return; } this.dc.onopen = () => { if (this.dc.readyState === 'open') { this.sendDCMessage(); } else { console.error('[DC] can"t send current state: ', this.dc.readyState); } }; } private dataChannelOnData(data: any) { if (!this.isJson(data)) { return; } const messageObj: MessageData = JSON.parse(data); // console.log('[dc] GOT message: ', messageObj); if (messageObj.feed) { if (!messageObj.type) { return; } if (messageObj.type === 'audio') { this.micState$.next({ userId: messageObj.feed, enabled: messageObj.enabled}); this.micStates[messageObj.feed] = messageObj.enabled; // save states to keep data in service } else if (messageObj.type === 'video' && messageObj.feed !== this.localUserId) { // don't allow controll cam from remote // console.log('[Js] messageObj.feed: ', messageObj.feed, ' localUserId: ', this.localUserId); this.camState$.next({ userId: messageObj.feed, enabled: messageObj.enabled}); this.camStates[messageObj.feed] = messageObj.enabled; // save states to keep data in service } if (messageObj.type === 'audio' || messageObj.type === 'video') { if (!this.firstMessageSent) { this.sendDCMessage(); // message back on join with current state this.sendDCVideoMessage(); this.firstMessageSent = true; } } } else { // video handler } } private addPublishers(publishers: any) { for (const i in publishers) { const id = publishers[i].id; const display = publishers[i].display; const audio = publishers[i].audio_codec; const video = publishers[i].video_codec; this.userIds.push(id); this.newRemoteFeed(id, display, audio, video); } } public async roomExists(roomName: string): Promise<RoomExistsResponse> { await this.attachVideoRoomPlugin(); const roomId: any = this.roomIdFromName(roomName); const result: RoomExistsResponse = await new Promise<RoomExistsResponse>((resolve, reject) => { this.videoRoomPlugin.send({ message: { request: 'exists', room: roomId, }, success: (data: RoomExistsDto) => { resolve(data); }, error: (error: JanusErrorDto) => { console.error('Can\'t check if room exists', error); reject(error); }, }); }); return result; } public async createRoom(roomName: string): Promise<CreateRoomResponse> { await this.attachVideoRoomPlugin(); const result: CreateRoomResponse = await new Promise<CreateRoomResponse>((resolve, reject) => { this.videoRoomPlugin.send({ message: { request: 'create', room: this.roomIdFromName(roomName), description: roomName, publishers: 30, audiocodec: 'opus', videocodec: 'h264', h264_profile: '42e01f', bitrate: this.customizationService.config.bitrate, bitrate_cap: true, audiolevel_ext: true, audiolevel_event: true, audio_active_packets: 100, audio_level_average: 40, notify_joining: true, videoorient_ext: true, fir_freq: 1, }, success: (data: CreateRoomDto) => { resolve(data); }, error: (error: JanusErrorDto) => { console.error('Can\'t create room', error); reject(error); }, }); }); return result; } public publishAboutJoin(userName: string): Observable<any> { return new Observable((observer: Observer<any>) => { this.videoRoomPlugin.send({ message: { request: 'publish', display: userName, audiocodec: 'opus', videocodec: 'h264', audio_level_average: 40, audio_active_packets: 25, audio: true, video: true, data: true, keyframe: true, }, success: (data: any) => { observer.next(data); }, error: ((err: any) => { observer.error(err); }), }); }); } public async joinRoom(roomId: any, userName: string): Promise<JoinRoomResponse> { try { await this.attachVideoRoomPlugin(); } catch (error) { console.log('[Join] attachVideoRoomPlugin error: ', error); return Promise.reject(); } const result: JoinRoomResponse = await new Promise<JoinRoomResponse>((resolve, reject) => { this.videoRoomPlugin.send({ message: { request: 'join', ptype: 'publisher', room: roomId, display: userName, id: environment.janus.stringRoomIds ? this.localUserId.toString() : this.localUserId, keyframe: true, }, success: (data: JoinRoomDto) => { resolve(data); }, error: (error: JanusErrorDto) => { console.error('Can\'t join room', error); reject(error); }, }); }); return result; } public async getRoomsList(): Promise<void> { // TODO: specify dto type try { await this.attachVideoRoomPlugin(); } catch (error) { return Promise.reject(); } const result: Promise<any> = await new Promise<any>((resolve, reject) => { // TODO: any this.videoRoomPlugin.send({ message: { request: 'list', }, success: (data: any) => { resolve(data); }, error: (error: JanusErrorDto) => { console.error('Can\'t get room list'); reject(error); }, }); }); return result; } public sendVideo(send = true): any { const media = !!send ? { addVideo: true, video: true } as any : { removeVideo: true }; if (!!media.addVideo) { media.video = this.stateService.videoDeviceId ? this.media.getSettingsForOffer() : true; } if (!this.stateService.isMicEnabled) { media.removeAudio = true; } else { media.audio = true; } // ---- media Stream const stream = this.localStream$.value; // : MediaStream if (media.removeVideo && !media.addVideo) { const videoTrack = (stream as MediaStream).getVideoTracks()[0]; if (videoTrack) { videoTrack.enabled = false; } this.stateService.videoEnabled = false; this.mutes.next({ type: 'video', on: false }); // send DCMessage return; } else if (media.addVideo) { const videoTrack = stream ? (stream as MediaStream).getVideoTracks()[0] : null; if (videoTrack) { videoTrack.enabled = true; this.stateService.videoEnabled = true; } this.mutes.next({ type: 'video', on: true }); // send DCMessage } // ---- EOF media Stream } public replaceVideo(stream: MediaStream): any { const settings = this.media.getSettingsForOffer(stream); stream.getTracks().forEach((track) => track.stop()); console.log('replace video'); this.videoRoomPlugin.createOffer({ media: { replaceVideo: true, video: settings, }, success: (jsep: any) => { (this.videoRoomPlugin as any).send({ message: { audioSend: true, videoSend: true }, jsep }); // ---- media Stream: Sync Enabled state for streams const streamValue = this.localStream$.value; const videoTrack = (streamValue as MediaStream).getVideoTracks()[0]; videoTrack.enabled = this.stateService.videoEnabled; this.mutes.next({ type: 'video', on: this.stateService.videoEnabled }); const audioTrack = (streamValue as MediaStream).getAudioTracks()[0]; audioTrack.enabled = this.stateService.audioEnabled; this.mutes.next({ type: 'audio', on: this.stateService.audioEnabled }); // ---- EOF media Stream }, error: (error: any) => { console.error('[replaceVideo] error', error); }, }); } public sendAudio(send = true): any { const media = !!send ? { addAudio: true, audio: true } as any : { removeAudio: true }; if (!!media.addAudio) { media.audio = this.stateService.audioDeviceId ? { deviceId: this.stateService.audioDeviceId } : true; } if (!this.stateService.isCamEnabled) { media.removeVideo = true; } // ---- media Stream const stream = this.localStream$.value; // : MediaStream if (media.removeAudio && !media.addAudio) { const audioTrack = (stream as MediaStream).getAudioTracks()[0]; audioTrack.enabled = false; this.stateService.audioEnabled = false; // send DCMessage } else if (media.addAudio) { // console.log('[sendAudio] Add media', media); const audioTrack = stream ? (stream as MediaStream).getAudioTracks()[0] : null; if (audioTrack) { audioTrack.enabled = true; this.stateService.audioEnabled = true; } // send DCMessage } this.mutes.next({ type: 'audio', on: !!this.stateService.audioEnabled }); // ---- EOF media Stream } public async createOffer(parameters: any, stream?: MediaStream): Promise<void> { // TODO: any // Wait until video room plugin will be available await this.attachVideoRoomPluginPromise; const pluginHandler = parameters.shareScreen ? this.videoRoomScreenSharePlugin : this.videoRoomPlugin; const media: any = parameters.shareScreen ? { // TODO: any video: 'screen', // Enable screen share audioSend: false, // Do or do not send audio videoRecv: false, // Do or do not receive video } : { audioRecv: true, // Do or do not receive audio videoRecv: true, // Do or do not receive video // force to true audioSend: true, // this.stateService.isMicEnabled, // Do or do not send audio // force to true and later updated with stateService.videoEnabled videoSend: true, // this.stateService.isCamEnabled, // Do or do not send video data: true, }; if (parameters.audioDeviceId) { media.audio = { deviceId: { exact: parameters.audioDeviceId } }; } if (parameters.videoDeviceId) { media.video = { deviceId: { exact: parameters.videoDeviceId } }; } if (parameters.replaceAudio) { // This is only needed in case of a renegotiation media.replaceAudio = parameters.replaceAudio; } if (parameters.replaceVideo) { // This is only needed in case of a renegotiation media.replaceVideo = parameters.replaceVideo; } if (!parameters.shareScreen) { media.video = this.stateService.constraints.video; } if (this.stateService.isCamBanned) { // user Blocked access to cam media.audio = false; media.video = false; } let simulcast = null; if (this.stateService.simulcastEnabled) { if (this.platform.FIREFOX) { simulcast = { simulcast: true }; } else if (this.platform.BLINK) { simulcast = { simulcast2: true }; } } console.log('[CreateOffer] simulcast media: ', media); pluginHandler.createOffer( { media, ...simulcast, success: (jsep: JanusJS.JSEP) => { pluginHandler.send({ message: { request: 'configure', // Both forced to true - later handled with stateService flags audio: true, // parameters.shareScreen ? true : this.stateService.isMicEnabled, video: true, // parameters.shareScreen ? true : this.stateService.isCamEnabled }, jsep, }); // @here: enabled = false if (!this.stateService.videoEnabled) { this.videoEnabledFalse(); } if (!this.stateService.audioEnabled) { this.audioEnabledFalse(); } }, error: (error: JanusErrorDto) => { console.error('[js] Can\'t create offer', error); // User didn't give a permission to share his screen if (parameters.shareScreen) { this.stateService.isScreenShareEnabled$.next(false); } }, }); } private videoEnabledFalse() { const s = this.localStream$.value; // : MediaStream if (!s) { return; } const videoTrack = (s as MediaStream).getVideoTracks()[0]; if (videoTrack) { videoTrack.enabled = false; } this.stateService.videoEnabled = false; this.mutes.next({ type: 'video', on: false }); } private audioEnabledFalse() { const s = this.localStream$.value; // : MediaStream if (!s) { return; } const audioTrack = (s as MediaStream).getAudioTracks()[0]; if (audioTrack) { audioTrack.enabled = false; } audioTrack.enabled = false; this.stateService.audioEnabled = false; this.mutes.next({ type: 'audio', on: false }); } public newRemoteFeed(id: string, display: string, audio: string, video: string): void { // A new feed has been published, create a new plugin handle and attach to it as a subscriber let remoteFeed: any = null; // TODO: any this.janus.attach( { plugin: 'janus.plugin.videoroom', success: (pluginHandle: JanusJS.PluginHandle) => { remoteFeed = pluginHandle; remoteFeed.simulcastStarted = false; // We wait for the plugin to send us an offer const subscribe = { request: 'join', room: this.stateService.roomId, ptype: 'subscriber', feed: id, keyframe: true, offer_video: true, }; // For example, if the publisher is VP8 and this is Safari, let's avoid video if (Janus.webRTCAdapter.browserDetails.browser === 'safari' && (video === 'vp9' || (video === 'vp8' && !Janus.safariVp8))) { console.warn('Publisher is using ' + video + ', but Safari doesn\'t support it: disabling video'); subscribe.offer_video = false; } remoteFeed.videoCodec = video; remoteFeed.send({ message: subscribe }); }, error: (error: string) => { console.error('[newRemoteFeed] Can\'t attach video room plugin to Janus error: ', error); }, onmessage: (msg: any, jsep: any) => { // TODO: anys this.videoRoomPlugin.send({ message: { request: 'listparticipants', room: this.stateService.roomId, }, success: (data: { participants: Participants[] }) => { }, error: (error: any) => { // TODO: handle if can't find participant console.log('[listparticipants] error: ', error); }, }); const event = msg.videoroom; if (msg.error) { console.error('[msg] Error', msg.error); } else if (event) { if (event === 'attached') { // Subscriber created and attached remoteFeed.rfid = msg.id; remoteFeed.rfdisplay = msg.display; // if (!remoteFeed.spinner) { // // var target = document.getElementById('videoremote'+remoteFeed.rfindex); // // remoteFeed.spinner = new Spinner({top:100}).spin(target); // } else { // // remoteFeed.spinner.spin(); // } // // // $('#remote'+remoteFeed.rfindex).removeClass('hide').html(remoteFeed.rfdisplay).show(); } else if (event === 'event') { // Check if we got a simulcast-related event from this publisher // const substream = msg.substream; // const temporal = msg.temporal; // if ((substream !== null && substream !== undefined) || (temporal !== null && temporal !== undefined)) { // if (!remoteFeed.simulcastStarted) { // remoteFeed.simulcastStarted = true; // } // } } else { // What has just happened? } } if (jsep) { // Answer and attach remoteFeed.createAnswer({ jsep, media: { audioSend: false, videoSend: false, data: true }, // We want recvonly audio/video TODO: !!!! success: (jsepObj: JanusJS.JSEP) => { remoteFeed.send({ message: { request: 'start', room: this.stateService.roomId }, jsep: jsepObj }); }, error: (error: JanusErrorDto) => { console.error('[createAnswer] WebRTC error', error); }, }); } }, iceState: (state: string) => { // console.log('[S] ICE state of this WebRTC PC (feed #' + remoteFeed.rfindex + ') changed to ' + state); }, webrtcState: (on: boolean) => { // console.log('[S] Janus says this WebRTC PC (feed #' + remoteFeed.rfindex + ') is ' + (on ? 'up' : 'down') + ' now'); if (on) { this.configureDataChannel(); } }, onlocalstream: (stream: MediaStream) => { // The subscriber stream is recvonly, we don't expect anything here }, ondataopen: (data: string) => { // console.log('[S] The DataChannel is available! data: ', data); }, ondata: (data: any) => this.dataChannelOnData(data), onremotetrack: (mediaStreamTrack: MediaStreamTrack) => { const isRemoteFeedExists = this.videos.find((videoObj: Video) => videoObj.id === remoteFeed.rfid); if (!isRemoteFeedExists) { const knownId = this.userIds.find((userId) => userId === remoteFeed.rfid); // check if no publisher with this remoteFeed.rfid if (!knownId) { return; } const videoStream = new MediaStream(); videoStream.addTrack(mediaStreamTrack); this.videos = [...this.videos, { audioKindAdded: 'audio' === mediaStreamTrack.kind, videoKindAdded: 'video' === mediaStreamTrack.kind, stream: videoStream, pluginHandle: remoteFeed, id: remoteFeed.rfid, name: remoteFeed.rfdisplay, remote: true, type: VideoType.Video, // TODO: determine is it video or screen }]; } else { // already exist: check/add new track const stream = isRemoteFeedExists.stream; if ('video' === mediaStreamTrack.kind && isRemoteFeedExists.videoKindAdded === false) { stream.addTrack(mediaStreamTrack); isRemoteFeedExists.videoKindAdded = true; } if ('audio' === mediaStreamTrack.kind && isRemoteFeedExists.audioKindAdded === false) { stream.addTrack(mediaStreamTrack); isRemoteFeedExists.audioKindAdded = true; } } }, onremotestream: (streamObj: MediaStream) => { const isRemoteFeedExists = this.videos.find((videoObj: Video) => videoObj.id === remoteFeed.rfid); if (!isRemoteFeedExists) { this.videos = [...this.videos, { stream: streamObj, pluginHandle: remoteFeed, id: remoteFeed.rfid, name: remoteFeed.rfdisplay, remote: true, type: VideoType.Video, // TODO: determine is it video or screen }]; } // Show the video, hide the spinner and show the resolution when we get a playing event // $("#remotevideo"+remoteFeed.rfindex).bind("playing", function () { // // remoteFeed.spinner.stop(); // if (Janus.webRTCAdapter.browserDetails.browser === 'firefox') { // // Firefox Stable has a bug: width and height are not immediately available after a playing // } // }); // Janus.attachMediaStream($('#remotevideo'+remoteFeed.rfindex).get(0), stream); // const videoTracks = stream.getVideoTracks(); // if (!videoTracks || videoTracks.length === 0) { // // No remote video // } else { // // Show video // } }, oncleanup: () => { }, }); } public startShareScreen(): void { // Screen share https://janus.conf.meetecho.com/screensharingtest.js?2 this.janus.attach( { plugin: 'janus.plugin.videoroom', success: (pluginHandle: JanusJS.PluginHandle) => { this.videoRoomScreenSharePlugin = pluginHandle; this.localScreenShareId = this.getRandomId(); this.camStates[this.localScreenShareId] = true; // Warn All, that screen not muted this.videoRoomScreenSharePlugin.send({ message: { request: 'join', room: this.stateService.roomId, ptype: 'publisher', display: this.stateService.userName + ' screen', id: this.localScreenShareId, }, }); }, error: (error: string) => { console.error('Can\'t attach video room plugin to Janus for screen share, error: ', error); }, consentDialog: (on: boolean) => { }, iceState: (state: string) => { }, mediaState: (medium: 'audio' | 'video', on: boolean) => { }, webrtcState: (on: boolean) => { }, onmessage: (msg: any, jsep: any) => { // TODO: anys const event = msg.videoroom; if (event) { if (event === 'joined') { this.createOffer({ shareScreen: true }); } else if (event === 'event') { console.log('[jS] Screen event', msg); } } if (jsep) { this.videoRoomScreenSharePlugin.handleRemoteJsep({ jsep }); } }, onlocaltrack: (mediaStreamTrack: MediaStreamTrack) => { const videoStream = new MediaStream(); videoStream.addTrack(mediaStreamTrack); this.videos = [...this.videos, { stream: videoStream, pluginHandle: this.videoRoomScreenSharePlugin, id: this.localScreenShareId, name: this.stateService.userName + ' screen', remote: false, type: VideoType.Screen, }]; // User stop screen sharing mediaStreamTrack.onended = () => { this.stateService.isScreenShareEnabled$.next(false); this.videoRoomScreenSharePlugin.detach(null); }; }, onlocalstream: (stream: MediaStream) => { this.videos = [...this.videos, { stream, pluginHandle: this.videoRoomScreenSharePlugin, id: this.localScreenShareId, name: this.stateService.userName + ' screen', remote: false, type: VideoType.Screen, }]; // User stop screen sharing stream.getVideoTracks()[0].onended = () => { this.stateService.isScreenShareEnabled$.next(false); this.videoRoomScreenSharePlugin.detach(null); }; }, onremotestream: (stream: MediaStream) => { }, oncleanup: () => { }, detached: () => { }, }); } public stopShareScreen(): void { this.videoRoomScreenSharePlugin.detach(null); } public roomIdFromName = (roomName: string): any => { const roomIdNumber = this.hashCode(roomName); return environment.janus.stringRoomIds ? `${roomIdNumber}` : roomIdNumber; } public hashCode = (s: string): number => { const md5: string = Md5.init(s); let hash = 0; for (let i = 0; i < md5.length; i++) { const character = md5.charCodeAt(i); // tslint:disable-next-line:no-bitwise hash = ((hash << 5 >>> 0) - hash) + character; // tslint:disable-next-line:no-bitwise hash = hash >>> 0; // Convert to 32bit integer } return hash; } public getRandomId(): number { return Math.floor(1000000000000000 + Math.random() * 9000000000000000); } public switchMic(on: boolean): void { if (on) { this.videoRoomPlugin.unmuteAudio(); } else { this.videoRoomPlugin.muteAudio(); } } public switchCam(on: boolean): void { if (on) { this.videoRoomPlugin.unmuteVideo(); } else { this.videoRoomPlugin.muteVideo(); } } public switchShareScreen(on: boolean): void { if (on) { this.startShareScreen(); } else { this.stopShareScreen(); } } createCsFabric(): void { const fabricAttributes = { remoteEndpointType: callstats.endpointType.peer, fabricTransmissionDirection: callstats.transmissionDirection.sendrecv, }; callstats.addNewFabric(this.getVideoRoomPC(), this.stateService.userName, callstats.fabricUsage.multiplex, this.stateService.roomId, fabricAttributes); } public getVideoRoomPC() { return this.videoRoomPlugin.webrtcStuff.pc; } public finishCall(): void { this.videoRoomPlugin.send({ message: { request: 'hangup' } }); this.videoRoomPlugin.hangup(); // TODO: clean this class properties } private isJson(str: string) { try { JSON.parse(str); } catch (e) { return false; } return true; } }
Trembit/lite.vatra.com
src/app/stusan/models/create-room.dto.ts
<gh_stars>0 import { JanusErrorDto } from './janus-error.dto'; export interface CreateRoomDto { videoroom: 'created'; room: number; // <unique numeric ID> permanent: boolean; // <true if saved to config file, false if not> } export type CreateRoomResponse = CreateRoomDto | JanusErrorDto;
Trembit/lite.vatra.com
src/app/stusan/shared/services/settings.service.ts
import { Injectable } from '@angular/core'; import { Observable, from, Observer, BehaviorSubject, Subject, merge } from 'rxjs'; import { map } from 'rxjs/operators'; const isSetsEqual = (a: any, b: any) => a.size === b.size && [...a].every(value => b.has(value)); @Injectable({ providedIn: 'root', }) export class SettingsService { private devices$ = new BehaviorSubject<MediaDeviceInfo[]>([]); get devices(): MediaDeviceInfo[] { return this.devices$.getValue(); } constructor() { this.updateDevices(); navigator.mediaDevices.ondevicechange = async () => { // device list changed (eg. user disconnected usb mic) await this.updateDevices(); }; } updateDevices(): Promise<boolean> { return this.getAllDevices().then(devices => { if (!isSetsEqual(new Set(devices), new Set(this.devices))) { this.devices$.next(devices); } return true; }).catch(error => { console.log('[settings] error: ', error); return false; }); } getLabelByKind(kind: string): string { let label: string; switch (kind) { case 'videoinput': label = 'Camera'; break; case 'audioinput': label = 'Microphone'; break; case 'audiooutput': label = 'Speaker'; break; default: label = 'Device'; break; } return label; } private getAllDevices(): Promise<MediaDeviceInfo[]> { return navigator.mediaDevices.enumerateDevices().then(devices => { const countByType = { audioinput: 0, videoinput: 0, audiooutput: 0 }; return devices.map(device => { let label = device.label; if (label === '') { label = `${this.getLabelByKind(device.kind)} #${countByType[device.kind]++}`; } return { ...device.toJSON(), label }; }).filter(device => device.deviceId.length > 32); }); } getDefaultAudioDevice(): Promise<MediaDeviceInfo | null> { return this.getDefaultDevice('audio'); } getDefaultVideoDevice(): Promise<MediaDeviceInfo | null> { return this.getDefaultDevice('video'); } getDefaultDevice(type: 'audio' | 'video'): Promise<MediaDeviceInfo | null> { return navigator.mediaDevices.enumerateDevices().then(devices => { const kind = type === 'audio' ? 'audioinput' : 'videoinput'; devices = devices.filter(device => device.kind === kind); const defaultDevice = devices.find(device => device.deviceId === 'default'); if (defaultDevice) { const realDevice = devices.find((device) => { return device.deviceId !== 'default' && device.groupId === defaultDevice.groupId && defaultDevice.label.endsWith(device.label); }); if (realDevice) { return realDevice; } } return null; }); } public getDevices(): Observable<{ videoDevices: Array<MediaDeviceInfo>, audioDevices: Array<MediaDeviceInfo> }> { return this.devices$.pipe(map((devices) => { return { audioDevices: devices.filter((device) => device.kind === 'audioinput'), videoDevices: devices.filter((device) => device.kind === 'videoinput'), }; })); } }
Trembit/lite.vatra.com
src/app/stusan/models/janus-error.dto.ts
<reponame>Trembit/lite.vatra.com export interface JanusErrorDto { videoroom: 'event'; error_code: number; // <numeric ID, check Macros below> error: string; // <error description as a string> }
Trembit/lite.vatra.com
src/app/stusan/room/room.module.ts
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RoomRoutingModule } from './room-routing.module'; import { SharedModule } from '@shared/shared.module'; import { RoomComponent } from './room.component'; import { HeaderComponent } from './header/header.component'; import { ControlsComponent } from './controls/controls.component'; import { VideosComponent } from './videos/videos.component'; import { ChatComponent } from './chat/chat.component'; @NgModule({ declarations: [ RoomComponent, HeaderComponent, ControlsComponent, VideosComponent, ChatComponent, ], imports: [ CommonModule, FormsModule, ReactiveFormsModule, RoomRoutingModule, SharedModule, ], }) export class RoomModule { }
Trembit/lite.vatra.com
src/app/stusan/shared/services/media.service.ts
import { Injectable } from '@angular/core'; import defaultsDeep from 'lodash.defaultsdeep'; import { BehaviorSubject } from 'rxjs'; import { StateService } from './state.service'; export type Resolution = { name: string; width: number; height: number; alt?: number; }; export const RESOLUTIONS: Resolution[] = [ { name: 'SD', width: 320, height: 240, alt: 180 }, { name: 'HQ', width: 640, height: 480, alt: 360 }, { name: 'HD', width: 1280, height: 960, alt: 720 }, ]; @Injectable({ providedIn: 'root', }) export class MediaService { camera$ = new BehaviorSubject<MediaStream | null>(null); set camera(stream: MediaStream | null) { if (stream === null) { this.camera?.getTracks().forEach((track) => track.stop()); } else { this.saveConstraints(stream); } this.camera$.next(stream); } get camera(): MediaStream | null { return this.camera$.getValue(); } get cameraIsAlive(): boolean { const video = this.camera?.getVideoTracks()[0]; if (video) { return video.readyState === 'live'; } return false; } private defaultsContraints: MediaStreamConstraints = { video: { aspectRatio: 1.77777777778, width: 640, height: 360, frameRate: 24, }, audio: true, }; private prevConstraints: MediaStreamConstraints = this.state.constraints; constructor(private state: StateService) { this.state.videoDeviceId$.subscribe((deviceId) => { if (!!deviceId) { defaultsDeep(this.defaultsContraints, { video: { deviceId: { exact: deviceId } } }); } }); this.state.audioDeviceId$.subscribe((deviceId) => { if (!!deviceId) { defaultsDeep(this.defaultsContraints, { audio: { deviceId: { exact: deviceId } } }); } }); } async getMediaStream(options?: MediaStreamConstraints): Promise<MediaStream> { const constraints = {}; defaultsDeep(constraints, options, this.prevConstraints, this.defaultsContraints); return navigator.mediaDevices.getUserMedia(constraints); } devicesGetUserMedia() { navigator.mediaDevices.getUserMedia({ audio: true, video: true }) .then((stream) => { // console.log('[ms] stream: ', stream) }) .catch((error) => { if ('NotAllowedError' === error.name) { // User blocked cam this.state.isCamBanned = true; } else if ('NotFoundError' === error.name) { // user don't have cam this.state.isCamBanned = true; } }); } saveConstraints(stream: MediaStream) { this.prevConstraints = { video: this.getSettingsForOffer(stream) || undefined }; this.state.constraints = this.prevConstraints; } getSettingsForOffer(stream?: MediaStream | null): { deviceId?: string, width?: number, height?: number } | null { if (stream) { const video = stream.getVideoTracks()[0]; if (video) { if (video.readyState === 'live') { const settings = video.getSettings(); return { width: settings.width, height: settings.height, deviceId: settings.deviceId, }; } else { if (this.prevConstraints) { const settings = (this.prevConstraints.video as any); return { width: settings.width, height: settings.height, deviceId: settings.deviceId, }; } } } } else { if (this.prevConstraints) { const settings = (this.prevConstraints.video as any); if (settings) { return { width: settings.width, height: settings.height, deviceId: settings.deviceId, }; } } } return null; } private isResolutionSupported(track: MediaStreamTrack, resolution: Resolution, onlyWidth = false, alternateHeight = false ): Promise<boolean> { if (resolution.width && resolution.height) { const constraints: MediaTrackConstraints = { width: { exact: resolution.width }, height: resolution.height, }; if (!onlyWidth) { constraints.height = { exact: resolution.height }; } if (alternateHeight) { constraints.height = { exact: resolution.alt }; } return track.applyConstraints(constraints).then(() => { return true; }).catch(async (error) => { if (error.name === 'OverconstrainedError' && error.constraint === 'height' && !alternateHeight) { return await this.isResolutionSupported(track, resolution, onlyWidth, true); } else { return false; } }); } else { return Promise.resolve(false); } } async getSupportedResolutions(stream: MediaStream, onlyWidth = false): Promise<any[]> { const supported: Resolution[] = []; const videoTrack = stream.getVideoTracks()[0]; if (videoTrack) { if (videoTrack.getCapabilities) { const capabilities: any = videoTrack.getCapabilities() || null; if (capabilities) { return Promise.resolve(RESOLUTIONS.filter((resolution) => { let comparator = capabilities.width.max >= resolution.width && capabilities.width.min <= resolution.width; if (!onlyWidth) { comparator = capabilities.width.max >= resolution.width && capabilities.width.min <= resolution.width && capabilities.height.max >= resolution.height && capabilities.height.min <= resolution.height; } return comparator; })); } } else { return Promise.resolve(RESOLUTIONS); } } return Promise.resolve(supported); } async getSupportedResolutionsByApplying(incomingStream: MediaStream, onlyWidth = false): Promise<any[]> { const stream = incomingStream.clone(); const supported: any[] = []; const videoTrack = stream.getVideoTracks()[0]; if (videoTrack) { for (const resolution of RESOLUTIONS) { if (await this.isResolutionSupported(videoTrack, resolution, onlyWidth)) { supported.push(resolution); } } /* Concurrent version seems buggy supported = await Promise.all(RESOLUTIONS.map(async (resolution) => { return this.isResolutionSupported(videoTrack, resolution, onlyWidth).then((supported) => { return supported ? resolution : false; }); })); supported = supported.filter(supported => !!supported); */ // this.stopStream(stream); return supported; } else { this.stopStream(stream); return Promise.resolve([]); } } getStreamResolution(stream: MediaStream): Resolution | null { const videoTrack = stream.getVideoTracks()[0]; if (videoTrack) { const settings = videoTrack.getSettings(); return RESOLUTIONS.find((resolution) => { return resolution.width === settings.width && (resolution.height === settings.height || resolution.alt === settings.height); }) || null; } return null; } getStreamVideoId(stream: MediaStream): string | null { const videoTrack = stream.getVideoTracks()[0]; if (videoTrack) { const settings = videoTrack.getSettings(); return settings.deviceId || null; } return null; } getStreamAudioId(stream: MediaStream): string | null { const audioTrack = stream.getAudioTracks()[0]; if (audioTrack) { const settings = audioTrack.getSettings(); return settings.deviceId || null; } return null; } applyResolution(stream: MediaStream, resolution: Resolution, alternateHeight = false): Promise<boolean> { const videoTrack = stream.getVideoTracks()[0]; if (videoTrack) { const constraints = { width: { exact: resolution.width }, height: { exact: alternateHeight ? resolution.alt : resolution.height }, }; return videoTrack.applyConstraints(constraints).then(() => true).catch(async (error) => { if (error.name === 'OverconstrainedError' && error.constraint === 'height' && !alternateHeight) { return await this.applyResolution(stream, resolution, true); } else { return false; } }); } return Promise.resolve(false); } stopStream(stream: MediaStream) { if (stream) { stream.getTracks().forEach((track) => track.stop()); } } }
Trembit/lite.vatra.com
src/app/stusan/shared/components/control-button/control-button.component.ts
<gh_stars>0 import { Component, ChangeDetectionStrategy, Input } from '@angular/core'; @Component({ selector: 'stusan-control-button', templateUrl: './control-button.component.html', styleUrls: ['./control-button.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) export class ControlButtonComponent { @Input() label: string; @Input() iconBg: string; @Input() iconColor: string; @Input() ariaLabel?: string; }
Trembit/lite.vatra.com
src/app/stusan/models/text-message.dto.ts
export interface MicState { userId: number; enabled: boolean; } export interface MessageData { feed: number; enabled: boolean; type: string; } export interface MicStates { [key: string]: boolean; }
Trembit/lite.vatra.com
src/app/stusan/services/customization.service.ts
<gh_stars>0 import { Injectable } from '@angular/core'; import { environment } from 'src/environments/environment'; import { CustomizationModel } from '../models/customization.model'; @Injectable({ providedIn: 'root' }) export class CustomizationService { readonly siriusHost = 'grouproom.sirius.video'; // readonly siriusHost = 'localhost'; // for tests config: CustomizationModel = { homeLogo: '/assets/stusan/images/logo.png', // if null - hide logo roomLogo: '/assets/stusan/images/stusan-logo-small.svg', homeShowDescription: {ideal: true}, // true by default, false for grouproom.sirius.video. mediaEchoCancellation: {ideal: true}, // by default mediaAutoGainControl: {ideal: true}, // by default mediaNoiseSuppression: {ideal: true}, // by default favicon: 'favicon.ico', server: environment.janus.server, bitrate: 768000, title: 'TheVatra', }; constructor() { // console.log('[Custom] constr hostname: ', window.location.hostname); if (this.isSirius()) { // this.config.homeLogo = '/assets/stusan/images/sirius.logo.png'; this.config.homeLogo = '/assets/stusan/images/sirius.home.logo.png'; // oct-18 this.config.roomLogo = '/assets/stusan/images/sirius.room.logo.png'; this.config.homeShowDescription = false; this.config.mediaAutoGainControl = false; this.config.mediaNoiseSuppression = false; this.config.favicon = './assets/favicon/favicon-sirius.png'; this.config.title = 'Sirius video'; this.config.server = 'wss://grouproom-media-wss.sirius.video:443'; this.config.bitrate = 128000; // 128 kbps } } public isSirius(): boolean { return window.location.hostname.indexOf(this.siriusHost) !== -1; } }
msage-godaddy/cypress-web-vitals
commands.d.ts
<gh_stars>1-10 /// <reference types="cypress" /> declare namespace Cypress { interface WebVitalsThresholds { /** * Largest contentful paint. * @see https://web.dev/lcp/ */ lcp?: number; /** * First input delay. * @see https://web.dev/fid/ */ fid?: number; /** * Cumulative layout shift. * @see https://web.dev/cls/ */ cls?: number; /** * First contentful paint. * @see https://web.dev/fcp/ */ fcp?: number; /** * Time to first byte. * @see https://web.dev/time-to-first-byte/ */ ttfb?: number; } interface WebVitalsConfig { /** * Thresholds to compare against captured web-vitals metrics. */ thresholds?: WebVitalsThresholds; /** * Url of page for auditing web-vitals. If not provided will * attempt to discover the current url using `cy.url()`. */ url?: string; /** * Selector used for capturing FID. * @default "body" */ firstInputSelector?: string; /** * Time in ms to wait for web-vitals to be reported before failing. * @default 10000 */ vitalsReportedTimeout?: number; } interface Chainable<Subject> { /** * Runs a web-vitals audit * @example * cy.vitals({ thresholds, url, selector }); * @param {WebVitalsConfig} webVitalsConfig configuration */ vitals(webVitalsConfig: WebVitalsConfig); } }
rylphs/TsUML
src/demo/main.ts
import { Ninja } from "./ninja"; import { Katana } from "./katana"; const ninja = new Ninja(new Katana()); ninja.fight(5);
rylphs/TsUML
src/core/templates.ts
import { PropertyDetails, MethodDetails} from "./interfaces"; export const templates = { composition: "+->", implementsOrExtends: (abstraction: string, implementation: string) => { return ( `${templates.plainClassOrInterface(abstraction)}` + `^-${templates.plainClassOrInterface(implementation)}` ); }, plainClassOrInterface: (name: string) => `[${name}]`, colorClass: (name: string) => `[${name}{bg:skyblue}]`, colorInterface: (name: string) => `[${name}{bg:palegreen}]`, class: (name: string, props: PropertyDetails[], methods: MethodDetails[]) => { const filterTracked = (property: PropertyDetails) => !property.tracked; const pTemplate = (property: PropertyDetails) => `${property.name}:${property.type};`; const mTemplate = (method: MethodDetails) => `${method.name}();`; return ( `${templates.colorClass(name)}` + `[${name}|${props.filter(filterTracked).map(pTemplate).join("")}|${methods.map(mTemplate).join("")}]` ); }, interface: ( name: string, props: PropertyDetails[], methods: MethodDetails[] ) => { const pTemplate = (property: PropertyDetails) => `${property.name};`; const mTemplate = (method: MethodDetails) => `${method.name}();`; return ( `${templates.colorInterface(name)}` + `[${name}|${props.map(pTemplate).join("")}|${methods.map(mTemplate).join("")}]` ); }, associations: (name:string, props: PropertyDetails[]) => { const filterNonTracked = (property: PropertyDetails) => property.tracked; return props.filter(filterNonTracked).reduce((v:string, curr: PropertyDetails)=> { if(!curr.type) return v; return `${v},[${name}]-${curr.name}>[${curr.type}]` }, ""); } };
rylphs/TsUML
src/core/interfaces.ts
<filename>src/core/interfaces.ts<gh_stars>0 export interface MethodDetails { name: string; } export interface PropertyDetails { name: string; type: string; tracked: boolean; } export interface HeritageClause { clause: string; className: string; }
rylphs/TsUML
src/core/emitter.ts
import Ast, * as SimpleAST from "ts-simple-ast"; import * as ts from "typescript"; import { flatten, join } from "lodash"; import * as path from "path"; import { PropertyDetails, MethodDetails, HeritageClause } from "./interfaces"; import { templates }from "./templates"; import { download } from "./io"; export function emitSingleClass(name: string, properties: PropertyDetails[], methods: MethodDetails[]) { console.log("emitingsingleclass: " + name); console.log(properties); return templates.class(name, properties, methods); } export function emitAssociations(name: string, properties: PropertyDetails[]) { return templates.associations(name, properties); } export function emitSingleInterface(name: string, properties: PropertyDetails[], methods: MethodDetails[]) { return templates.interface(name, properties, methods); } export function emitHeritageClauses(heritageClauses: HeritageClause[]) { return heritageClauses.map((heritageClause) => templates.implementsOrExtends(heritageClause.clause, heritageClause.className) ); }
rylphs/TsUML
src/core/parser.ts
<gh_stars>0 import Ast, * as SimpleAST from "ts-simple-ast"; import * as ts from "typescript"; import { flatten, join } from "lodash"; import { PropertyDetails, MethodDetails, HeritageClause } from "./interfaces"; export function getAst(tsConfigPath: string, sourceFilesPaths?: string[]) { const ast = new Ast({ tsConfigFilePath: tsConfigPath, addFilesFromTsConfig: !Array.isArray(sourceFilesPaths) }); if (sourceFilesPaths) { ast.addExistingSourceFiles(sourceFilesPaths); } return ast; } export function parseClasses(classDeclaration: SimpleAST.ClassDeclaration, trackedClasses: String[]) { const className = classDeclaration.getSymbol()!.getName(); const propertyDeclarations = classDeclaration.getProperties(); //console.log(propertyDeclarations); const methodDeclarations = classDeclaration.getMethods(); const properties = propertyDeclarations.map(property => { const sym = property.getSymbol(); if (sym) { var type = property.getType().getText(); return {name: sym.getName(), type: type, tracked:(trackedClasses.indexOf(type) > -1)} } }).filter((p) => p !== undefined) as PropertyDetails[]; const methods = methodDeclarations.map(method => { const sym = method.getSymbol(); if (sym) { return { name: sym.getName() } } }).filter((p) => p !== undefined) as MethodDetails[]; return { className, properties, methods }; } export function parseInterfaces(interfaceDeclaration: SimpleAST.InterfaceDeclaration) { const interfaceName = interfaceDeclaration.getSymbol()!.getName(); const propertyDeclarations = interfaceDeclaration.getProperties(); const methodDeclarations = interfaceDeclaration.getMethods(); const properties = propertyDeclarations.map(property => { const sym = property.getSymbol(); if (sym) { return { name: sym.getName() } } }).filter((p) => p !== undefined) as PropertyDetails[]; const methods = methodDeclarations.map(method => { const sym = method.getSymbol(); if (sym) { return { name: sym.getName() } } }).filter((p) => p !== undefined) as MethodDetails[]; return { interfaceName, properties, methods }; } export function parseHeritageClauses(classDeclaration: SimpleAST.ClassDeclaration) { const className = classDeclaration.getSymbol()!.getName(); const extended = classDeclaration.getExtends(); const implemented = classDeclaration.getImplements(); let heritageClauses: HeritageClause[] = []; if (extended) { const identifier = extended.getChildrenOfKind(ts.SyntaxKind.Identifier)[0]; if (identifier) { const sym = identifier.getSymbol(); if (sym) { heritageClauses.push( { clause: sym.getName(), className } ); } } } if (implemented) { implemented.forEach(i => { const identifier = i.getChildrenOfKind(ts.SyntaxKind.Identifier)[0]; if (identifier) { const sym = identifier.getSymbol(); if (sym) { heritageClauses.push( { clause: sym.getName(), className } ); } } }); } return heritageClauses; }