├── .eslintignore ├── .eslintrc.json ├── .github └── workflows │ ├── production.yml │ └── staging.yml ├── .gitignore ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── LICENSE ├── README.md ├── charts └── fbw-api │ ├── Chart.yaml │ ├── environments │ ├── production.yaml │ └── staging.yaml │ ├── templates │ ├── deployment.yaml │ ├── ingress.yaml │ ├── secret.yaml │ ├── service-account.yaml │ └── service.yaml │ └── values.yaml ├── docker-compose.yml ├── nest-cli.json ├── package-lock.json ├── package.json ├── scripts └── secrets.js ├── src ├── airport │ ├── airport-augmentation.entity.ts │ ├── airport.controller.spec.ts │ ├── airport.controller.ts │ ├── airport.module.ts │ ├── airport.service.spec.ts │ ├── airport.service.ts │ └── dto │ │ ├── airport-batch.dto.ts │ │ └── airport.dto.ts ├── app.controller.ts ├── app.module.ts ├── atc │ ├── atc-info.class.ts │ ├── atc.controller.ts │ └── atc.service.ts ├── atis │ ├── atis.class.ts │ ├── atis.controller.spec.ts │ ├── atis.controller.ts │ ├── atis.service.spec.ts │ └── atis.service.ts ├── auth │ ├── auth.module.ts │ ├── auth.service.spec.ts │ ├── auth.service.ts │ └── flights │ │ ├── flight-auth-guard.service.ts │ │ ├── flight-auth.guard.spec.ts │ │ ├── flight-token.class.ts │ │ └── flight.strategy.ts ├── cache │ ├── cache.module.ts │ └── cache.service.ts ├── charts │ ├── charts.controller.spec.ts │ ├── charts.controller.ts │ ├── charts.module.ts │ ├── charts.service.spec.ts │ ├── charts.service.ts │ └── dto │ │ ├── chart.dto.ts │ │ └── charts.dto.ts ├── common │ ├── Bounds.ts │ └── Pagination.ts ├── config │ └── configuration.ts ├── cpdlc │ ├── cpdlc.class.ts │ ├── cpdlc.controller.spec.ts │ ├── cpdlc.controller.ts │ ├── cpdlc.service.spec.ts │ ├── cpdlc.service.ts │ └── dto │ │ └── cpdlc-message.dto.ts ├── discord │ ├── discord.module.ts │ └── discord.service.ts ├── git-versions │ ├── dto │ │ ├── artifact-info.dto.ts │ │ ├── commit-info.dto.ts │ │ ├── pull-info.dto.ts │ │ ├── pull-label.dto.ts │ │ └── release-info.dto.ts │ ├── git-versions.controller.spec.ts │ ├── git-versions.controller.ts │ ├── git-versions.module.ts │ ├── git-versions.service.spec.ts │ └── git-versions.service.ts ├── gnss │ ├── dto │ │ └── satellite-info.dto.ts │ ├── gnss.controller.ts │ ├── gnss.module.ts │ └── gnss.service.ts ├── health │ ├── health.controller.ts │ └── health.module.ts ├── main.ts ├── metar │ ├── metar.class.ts │ ├── metar.controller.spec.ts │ ├── metar.controller.ts │ ├── metar.service.spec.ts │ └── metar.service.ts ├── taf │ ├── taf.class.ts │ ├── taf.controller.spec.ts │ ├── taf.controller.ts │ ├── taf.service.spec.ts │ └── taf.service.ts ├── telex │ ├── dto │ │ ├── create-telex-connection.dto.ts │ │ ├── paginated-telex-connection.dto.ts │ │ ├── telex-message.dto.ts │ │ ├── telex-search-result.dto.ts │ │ └── update-telex-connection.dto.ts │ ├── entities │ │ ├── blocked-ip.entity.ts │ │ ├── point.entity.ts │ │ ├── telex-connection.entity.ts │ │ └── telex-message.entity.ts │ ├── filters.ts │ ├── telex-connection.controller.ts │ ├── telex-message.controller.ts │ ├── telex.controller.spec.ts │ ├── telex.module.ts │ ├── telex.service.spec.ts │ └── telex.service.ts └── utilities │ ├── db-naming.ts │ ├── ip-address.decorator.ts │ ├── ivao.service.ts │ ├── not-found.filter.ts │ └── vatsim.service.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | scripts/ 2 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "env": { "browser": true }, 4 | "extends": "@flybywiresim/eslint-config", 5 | "plugins": ["@typescript-eslint"], 6 | "parser": "@typescript-eslint/parser", 7 | "parserOptions": { 8 | "ecmaVersion": 2021, 9 | "sourceType": "script", 10 | "requireConfigFile": false 11 | }, 12 | "settings": { 13 | "import/resolver": { 14 | "node": { 15 | "extensions": [".js", ".jsx", ".ts", ".tsx"] 16 | } 17 | } 18 | }, 19 | "overrides": [ 20 | { 21 | "files": ["*.mjs", "*.ts", "*.d.ts"], 22 | "parserOptions": { "sourceType": "module" } 23 | }, 24 | { 25 | "files": ["*.ts", "*.tsx"], 26 | "rules": { 27 | "no-undef": "off" 28 | } 29 | } 30 | ], 31 | // overrides airbnb, use sparingly 32 | "rules": { 33 | "object-curly-newline": ["error", { "multiline": true }], 34 | 35 | // Required for dependency injection 36 | "no-useless-constructor": "off", 37 | "no-empty-function": "off" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /.github/workflows/production.yml: -------------------------------------------------------------------------------- 1 | name: Production CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | lint_helm: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v1 13 | - name: Lint Helm 14 | run: helm lint ./charts/fbw-api 15 | build_and_push: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Docker meta 19 | id: docker_meta 20 | uses: crazy-max/ghaction-docker-meta@v1 21 | with: 22 | images: flybywiresim/api 23 | tag-sha: true 24 | tag-latest: false 25 | - name: Set up QEMU 26 | uses: docker/setup-qemu-action@v1 27 | - name: Set up Docker Buildx 28 | uses: docker/setup-buildx-action@v1 29 | - name: Login to DockerHub 30 | uses: docker/login-action@v1 31 | with: 32 | username: ${{ secrets.DOCKERHUB_USERNAME }} 33 | password: ${{ secrets.DOCKERHUB_TOKEN }} 34 | - name: Build and push 35 | id: docker_build 36 | uses: docker/build-push-action@v2 37 | with: 38 | cache-from: type=registry,ref=flybywiresim/api:main 39 | cache-to: type=inline 40 | push: true 41 | tags: ${{ steps.docker_meta.outputs.tags }} 42 | - name: Image digest 43 | run: echo ${{ steps.docker_build.outputs.digest }} 44 | deploy_production: 45 | runs-on: ubuntu-latest 46 | needs: [build_and_push, lint_helm] 47 | env: 48 | NAMESPACE: fbw-api-prod 49 | RELEASE_NAME: fbw-api-prod 50 | VALUES_FILE: ./charts/fbw-api/environments/production.yaml 51 | DB_PASSWORD: ${{ secrets.PROD_DB_PASSWORD }} 52 | AUTH_SECRET: ${{ secrets.PROD_AUTH_SECRET }} 53 | GITHUB_TOKEN: ${{ secrets.GH_API_TOKEN }} 54 | DISCORD_WEBHOOK: ${{ secrets.PROD_DISCORD_WEBHOOK }} 55 | steps: 56 | - uses: actions/checkout@v1 57 | - name: Install doctl 58 | uses: digitalocean/action-doctl@v2 59 | with: 60 | token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} 61 | - name: Save DigitalOcean kubeconfig 62 | run: doctl kubernetes cluster kubeconfig save ${{ secrets.DIGITALOCEAN_CLUSTER_ID }} 63 | - name: Deploy 64 | run: | 65 | TAG=$(echo $GITHUB_SHA | head -c7) && 66 | helm upgrade --namespace ${NAMESPACE} --set api.database.password=${DB_PASSWORD},api.auth.secret=${AUTH_SECRET},image.tag=sha-${TAG} \ 67 | --set api.github.token=${GITHUB_TOKEN},api.telex.discordWebhook=${DISCORD_WEBHOOK} \ 68 | -f ./charts/fbw-api/values.yaml -f ${VALUES_FILE} ${RELEASE_NAME} ./charts/fbw-api 69 | -------------------------------------------------------------------------------- /.github/workflows/staging.yml: -------------------------------------------------------------------------------- 1 | name: Staging CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - staging 7 | 8 | jobs: 9 | lint_helm: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v1 13 | - name: Lint Helm 14 | run: helm lint ./charts/fbw-api 15 | build_and_push: 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Docker meta 19 | id: docker_meta 20 | uses: crazy-max/ghaction-docker-meta@v1 21 | with: 22 | images: flybywiresim/api 23 | tag-sha: true 24 | tag-latest: false 25 | - name: Set up QEMU 26 | uses: docker/setup-qemu-action@v1 27 | - name: Set up Docker Buildx 28 | uses: docker/setup-buildx-action@v1 29 | - name: Login to DockerHub 30 | uses: docker/login-action@v1 31 | with: 32 | username: ${{ secrets.DOCKERHUB_USERNAME }} 33 | password: ${{ secrets.DOCKERHUB_TOKEN }} 34 | - name: Build and push 35 | id: docker_build 36 | uses: docker/build-push-action@v2 37 | with: 38 | cache-from: type=registry,ref=flybywiresim/api:staging 39 | cache-to: type=inline 40 | push: true 41 | tags: ${{ steps.docker_meta.outputs.tags }} 42 | - name: Image digest 43 | run: echo ${{ steps.docker_build.outputs.digest }} 44 | deploy_staging: 45 | runs-on: ubuntu-latest 46 | needs: [build_and_push, lint_helm] 47 | env: 48 | NAMESPACE: fbw-api-staging 49 | RELEASE_NAME: fbw-api-staging 50 | VALUES_FILE: ./charts/fbw-api/environments/staging.yaml 51 | DB_PASSWORD: ${{ secrets.STAGING_DB_PASSWORD }} 52 | AUTH_SECRET: ${{ secrets.STAGING_AUTH_SECRET }} 53 | GITHUB_TOKEN: ${{ secrets.GH_API_TOKEN }} 54 | DISCORD_WEBHOOK: ${{ secrets.STAGING_DISCORD_WEBHOOK }} 55 | steps: 56 | - uses: actions/checkout@v1 57 | - name: Install doctl 58 | uses: digitalocean/action-doctl@v2 59 | with: 60 | token: ${{ secrets.DIGITALOCEAN_ACCESS_TOKEN }} 61 | - name: Save DigitalOcean kubeconfig 62 | run: doctl kubernetes cluster kubeconfig save ${{ secrets.DIGITALOCEAN_CLUSTER_ID }} 63 | - name: Deploy 64 | run: | 65 | TAG=$(echo $GITHUB_SHA | head -c7) && 66 | helm upgrade --namespace ${NAMESPACE} --set api.database.password=${DB_PASSWORD},api.auth.secret=${AUTH_SECRET},image.tag=sha-${TAG} \ 67 | --set api.github.token=${GITHUB_TOKEN},api.telex.discordWebhook=${DISCORD_WEBHOOK} \ 68 | -f ./charts/fbw-api/values.yaml -f ${VALUES_FILE} ${RELEASE_NAME} ./charts/fbw-api 69 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # OS 14 | .DS_Store 15 | 16 | # Tests 17 | /coverage 18 | /.nyc_output 19 | 20 | # IDEs and editors 21 | /.idea 22 | .project 23 | .classpath 24 | .c9/ 25 | *.launch 26 | .settings/ 27 | *.sublime-workspace 28 | 29 | # IDE - VSCode 30 | .vscode/* 31 | !.vscode/settings.json 32 | !.vscode/tasks.json 33 | !.vscode/launch.json 34 | !.vscode/extensions.json 35 | 36 | # Secrets 37 | /secrets 38 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at contact@flybywiresim.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12.8-alpine as builder 2 | 3 | WORKDIR /app 4 | ENV NODE_ENV=development 5 | 6 | COPY package*.json ./ 7 | COPY tsconfig*.json ./ 8 | COPY .eslintrc.json ./ 9 | COPY .eslintignore ./ 10 | 11 | RUN npm install -g @nestjs/cli 12 | RUN npm install 13 | 14 | COPY src/ src/ 15 | RUN npm run build 16 | 17 | 18 | 19 | FROM node:12.8-alpine 20 | 21 | WORKDIR /app 22 | ENV NODE_ENV=production 23 | 24 | COPY --from=builder /app/dist ./dist 25 | COPY --from=builder /app/node_modules ./node_modules 26 | 27 | EXPOSE 3000 28 | 29 | HEALTHCHECK --interval=15s --timeout=3s --start-period=5s --retries=2 \ 30 | CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health \ 31 | || exit 1 32 | 33 | CMD [ "node", "dist/main.js" ] 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![FlyByWire Simulations](https://raw.githubusercontent.com/flybywiresim/branding/master/tails-with-text/FBW-Color-Dark.svg#gh-light-mode-only) 2 | ![FlyByWire Simulations](https://raw.githubusercontent.com/flybywiresim/branding/master/tails-with-text/FBW-Color-Light.svg#gh-dark-mode-only) 3 | 4 | ## FlyByWire Simulations API 5 | 6 | This repo contains the source code to our API which is used in all our products from the A32NX mod all the way to the website. The documentation can be found at https://api.flybywiresim.com/api. 7 | 8 | ## Developing 9 | 10 | Please make sure you have: 11 | 12 | NodeJS 14 - [Homepage](https://nodejs.org/en/) 13 | 14 | ```bash 15 | # install all dependencies 16 | $ npm install 17 | 18 | # start MySQL and Redis using docker-compose 19 | $ npm run compose 20 | 21 | # watch mode 22 | $ npm run start:dev 23 | ``` 24 | -------------------------------------------------------------------------------- /charts/fbw-api/Chart.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | appVersion: v0.0.1 3 | version: 0.0.1 4 | name: fbw-api 5 | description: FlyByWire Simulations API 6 | icon: https://raw.githubusercontent.com/flybywiresim/fbw-branding/master/svg/FBW-Logo.svg 7 | sources: 8 | - https://github.com/flybywiresim/api 9 | keywords: 10 | - fs2020 11 | - fbw 12 | home: http://flybywiresim.com 13 | -------------------------------------------------------------------------------- /charts/fbw-api/environments/production.yaml: -------------------------------------------------------------------------------- 1 | replicas: 4 2 | 3 | ingress: 4 | fqdn: api.flybywiresim.com 5 | tls: 6 | enabled: true 7 | issuer: letsencrypt-prod 8 | 9 | api: 10 | database: 11 | host: private-mysql-flybywiresim-do-user-8167919-0.b.db.ondigitalocean.com 12 | port: 25060 13 | database: fbw_api_prod 14 | user: fbw_api_prod 15 | redis: 16 | host: redis-prod-master.redis-prod.svc.cluster.local 17 | telex: 18 | timeoutMin: 6 19 | -------------------------------------------------------------------------------- /charts/fbw-api/environments/staging.yaml: -------------------------------------------------------------------------------- 1 | ingress: 2 | fqdn: api.staging.flybywiresim.com 3 | tls: 4 | enabled: true 5 | issuer: letsencrypt-prod 6 | 7 | api: 8 | database: 9 | host: private-mysql-flybywiresim-do-user-8167919-0.b.db.ondigitalocean.com 10 | port: 25060 11 | database: fbw_api_staging 12 | user: fbw_api_staging 13 | redis: 14 | host: redis-staging-master.redis-staging.svc.cluster.local 15 | telex: 16 | timeoutMin: 15 17 | disableCleanup: true 18 | -------------------------------------------------------------------------------- /charts/fbw-api/templates/deployment.yaml: -------------------------------------------------------------------------------- 1 | kind: Deployment 2 | apiVersion: apps/v1 3 | metadata: 4 | name: {{ .Release.Name }} 5 | labels: 6 | app.kubernetes.io/instance: {{ .Release.Name }} 7 | app.kubernetes.io/name: {{ .Chart.Name }} 8 | spec: 9 | replicas: {{ .Values.replicas }} 10 | selector: 11 | matchLabels: 12 | app.kubernetes.io/instance: {{ .Release.Name }} 13 | app.kubernetes.io/name: {{ .Chart.Name }} 14 | template: 15 | metadata: 16 | labels: 17 | app.kubernetes.io/instance: {{ .Release.Name }} 18 | app.kubernetes.io/name: {{ .Chart.Name }} 19 | spec: 20 | serviceAccountName: {{ .Release.Name }} 21 | containers: 22 | - name: fbw-api 23 | image: {{ .Values.image.repository }}:{{ .Values.image.tag }} 24 | imagePullPolicy: {{ .Values.image.pullPolicy }} 25 | ports: 26 | - name: http 27 | containerPort: {{ .Values.service.port }} 28 | protocol: TCP 29 | env: 30 | - name: NODE_ENV 31 | value: production 32 | 33 | # APM 34 | - name: ELASTIC_APM_ACTIVE 35 | value: {{ .Values.apm.active | quote }} 36 | - name: ELASTIC_APM_SERVER_URL 37 | value: {{ .Values.apm.serverUrl }} 38 | 39 | # LOGGER 40 | - name: LOGGER_LEVEL 41 | value: {{ .Values.api.logger.level }} 42 | - name: LOGGER_FORMAT 43 | value: {{ .Values.api.logger.format }} 44 | 45 | # DATABASE 46 | - name: DATABASE_HOST 47 | value: {{ .Values.api.database.host }} 48 | - name: DATABASE_PORT 49 | value: {{ .Values.api.database.port | quote }} 50 | - name: DATABASE_DATABASE 51 | value: {{ .Values.api.database.database }} 52 | - name: DATABASE_USERNAME 53 | value: {{ .Values.api.database.user }} 54 | - name: DATABASE_PASSWORD 55 | valueFrom: 56 | secretKeyRef: 57 | name: {{ .Release.Name }} 58 | key: databasePassword 59 | - name: DATABASE_LOGGING 60 | value: {{ .Values.api.database.logging }} 61 | - name: DATABASE_CONN_LIMIT 62 | value: {{ .Values.api.database.connectionLimit | quote }} 63 | {{- if .Values.api.database.replicas }} 64 | - name: DATABASE_READ_ONLY_HOSTS 65 | value: {{ range .Values.api.database.replicas }}{{ . }};{{ end }} 66 | {{- end }} 67 | 68 | # REDIS 69 | - name: REDIS_HOST 70 | value: {{ .Values.api.redis.host }} 71 | - name: REDIS_PORT 72 | value: {{ .Values.api.redis.port |quote }} 73 | 74 | # TELEX 75 | - name: TELEX_TIMEOUT_MIN 76 | value: {{ .Values.api.telex.timeoutMin | quote }} 77 | - name: TELEX_DISABLE_CLEANUP 78 | value: {{ .Values.api.telex.disableCleanup | quote }} 79 | - name: TELEX_DISCORD_WEBHOOK 80 | value: {{ .Values.api.telex.discordWebhook }} 81 | 82 | # AUTH 83 | - name: AUTH_SECRET 84 | valueFrom: 85 | secretKeyRef: 86 | name: {{ .Release.Name }} 87 | key: authSecret 88 | - name: AUTH_EXPIRES 89 | value: {{ .Values.api.auth.expires | quote }} 90 | 91 | # GITHUB 92 | - name: GITHUB_TOKEN 93 | valueFrom: 94 | secretKeyRef: 95 | name: {{ .Release.Name }} 96 | key: githubToken 97 | resources: 98 | requests: 99 | cpu: 100m 100 | memory: 90Mi 101 | limits: 102 | cpu: 1000m 103 | memory: 450Mi 104 | livenessProbe: 105 | httpGet: 106 | path: /health 107 | port: http 108 | scheme: HTTP 109 | initialDelaySeconds: 10 110 | timeoutSeconds: 10 111 | periodSeconds: 10 112 | successThreshold: 1 113 | failureThreshold: 3 114 | readinessProbe: 115 | httpGet: 116 | path: /health 117 | port: http 118 | scheme: HTTP 119 | initialDelaySeconds: 10 120 | timeoutSeconds: 10 121 | periodSeconds: 10 122 | successThreshold: 1 123 | failureThreshold: 3 124 | -------------------------------------------------------------------------------- /charts/fbw-api/templates/ingress.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: networking.k8s.io/v1 2 | kind: Ingress 3 | metadata: 4 | name: {{ .Release.Name }} 5 | labels: 6 | app.kubernetes.io/instance: {{ .Release.Name }} 7 | app.kubernetes.io/name: {{ .Chart.Name }} 8 | annotations: 9 | cert-manager.io/cluster-issuer: {{ .Values.ingress.tls.issuer }} 10 | spec: 11 | tls: 12 | - hosts: 13 | - {{ .Values.ingress.fqdn }} 14 | secretName: {{ .Release.Name }}-tls 15 | rules: 16 | - host: {{ .Values.ingress.fqdn }} 17 | http: 18 | paths: 19 | - path: / 20 | pathType: Prefix 21 | backend: 22 | service: 23 | name: {{ .Release.Name }} 24 | port: 25 | number: {{ .Values.service.port }} 26 | -------------------------------------------------------------------------------- /charts/fbw-api/templates/secret.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Secret 3 | metadata: 4 | name: {{ .Release.Name }} 5 | labels: 6 | app.kubernetes.io/instance: {{ .Release.Name }} 7 | app.kubernetes.io/name: {{ .Chart.Name }} 8 | type: Opaque 9 | data: 10 | databasePassword: {{ .Values.api.database.password | b64enc }} 11 | authSecret: {{ .Values.api.auth.secret | b64enc }} 12 | githubToken: {{ .Values.api.github.token | b64enc }} 13 | -------------------------------------------------------------------------------- /charts/fbw-api/templates/service-account.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: ServiceAccount 3 | metadata: 4 | name: {{ .Release.Name }} 5 | labels: 6 | app.kubernetes.io/instance: {{ .Release.Name }} 7 | app.kubernetes.io/name: {{ .Chart.Name }} 8 | -------------------------------------------------------------------------------- /charts/fbw-api/templates/service.yaml: -------------------------------------------------------------------------------- 1 | apiVersion: v1 2 | kind: Service 3 | metadata: 4 | name: {{ .Release.Name }} 5 | labels: 6 | app.kubernetes.io/instance: {{ .Release.Name }} 7 | app.kubernetes.io/name: {{ .Chart.Name }} 8 | spec: 9 | selector: 10 | app.kubernetes.io/instance: {{ .Release.Name }} 11 | app.kubernetes.io/name: {{ .Chart.Name }} 12 | ports: 13 | - protocol: TCP 14 | port: {{ .Values.service.port }} 15 | targetPort: {{ .Values.service.port }} 16 | -------------------------------------------------------------------------------- /charts/fbw-api/values.yaml: -------------------------------------------------------------------------------- 1 | image: 2 | repository: flybywiresim/api 3 | tag: latest 4 | pullPolicy: Always 5 | 6 | replicas: 1 7 | 8 | service: 9 | port: 3000 10 | 11 | ingress: 12 | fqdn: ~ 13 | tls: 14 | enabled: false 15 | issuer: ~ 16 | 17 | apm: 18 | active: false 19 | serverUrl: ~ 20 | 21 | api: 22 | logger: 23 | level: info 24 | format: json 25 | database: 26 | host: ~ 27 | port: 3306 28 | database: fbw 29 | user: fbw 30 | password: somePassword 31 | logging: error 32 | connectionLimit: 5 33 | replicas: [] 34 | redis: 35 | host: ~ 36 | port: 6379 37 | telex: 38 | disableCleanup: false 39 | timeoutMin: 6 40 | discordWebhook: ~ 41 | auth: 42 | secret: someSecret 43 | expires: 12h 44 | github: 45 | token: someToken 46 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.3" 2 | services: 3 | redis: 4 | image: redis:latest 5 | restart: unless-stopped 6 | ports: 7 | - 6379:6379 8 | 9 | mysql: 10 | image: mysql:latest 11 | restart: unless-stopped 12 | command: --default-authentication-plugin=mysql_native_password 13 | environment: 14 | - MYSQL_ROOT_PASSWORD_FILE=/run/secrets/db_root_password 15 | - MYSQL_DATABASE=fbw 16 | - MYSQL_USER=fbw 17 | - MYSQL_PASSWORD_FILE=/run/secrets/db_password 18 | secrets: 19 | - db_root_password 20 | - db_password 21 | ports: 22 | - 3306:3306 23 | 24 | secrets: 25 | db_password: 26 | file: secrets/db_password.txt 27 | db_root_password: 28 | file: secrets/db_root_password.txt 29 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "collection": "@nestjs/schematics", 3 | "sourceRoot": "src" 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "fbw-api", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "MIT", 8 | "scripts": { 9 | "compose": "docker-compose up -d", 10 | "postinstall": "node scripts/secrets.js", 11 | "prebuild": "rimraf dist", 12 | "build": "nest build", 13 | "start": "nest start", 14 | "start:dev": "nest start --watch", 15 | "start:debug": "nest start --debug --watch", 16 | "start:prod": "node dist/main", 17 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\"", 18 | "lint:fix": "npm run lint -- --fix", 19 | "test": "jest", 20 | "test:watch": "jest --watch", 21 | "test:cov": "jest --coverage", 22 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 23 | "test:e2e": "jest --config ./test/jest-e2e.json" 24 | }, 25 | "dependencies": { 26 | "@nestjs/common": "^7.0.0", 27 | "@nestjs/config": "^0.5.0", 28 | "@nestjs/core": "^7.0.0", 29 | "@nestjs/jwt": "^7.1.0", 30 | "@nestjs/passport": "^7.1.0", 31 | "@nestjs/platform-express": "^7.0.0", 32 | "@nestjs/schedule": "^0.4.1", 33 | "@nestjs/swagger": "^4.6.1", 34 | "@nestjs/terminus": "^7.0.1", 35 | "@nestjs/typeorm": "^7.1.4", 36 | "axios": "^0.20.0", 37 | "bad-words": "^3.0.3", 38 | "cache-manager": "^3.4.0", 39 | "cache-manager-redis-store": "^2.0.0", 40 | "class-transformer": "^0.3.1", 41 | "class-validator": "^0.12.2", 42 | "elastic-apm-node": "^3.9.0", 43 | "express-rate-limit": "^5.1.3", 44 | "helmet": "^4.1.1", 45 | "iconv-lite": "^0.6.2", 46 | "mysql": "^2.18.1", 47 | "nest-winston": "^1.4.0", 48 | "passport": "^0.4.1", 49 | "passport-jwt": "^4.0.0", 50 | "passport-local": "^1.0.0", 51 | "reflect-metadata": "^0.1.13", 52 | "request-ip": "^2.1.3", 53 | "rimraf": "^3.0.2", 54 | "rxjs": "^6.5.4", 55 | "swagger-ui-express": "^4.1.4", 56 | "typeorm": "^0.2.28", 57 | "winston": "^3.3.3" 58 | }, 59 | "devDependencies": { 60 | "@flybywiresim/eslint-config": "^0.1.0", 61 | "@nestjs/cli": "^7.0.0", 62 | "@nestjs/schematics": "^7.0.0", 63 | "@nestjs/testing": "^7.0.0", 64 | "@types/express": "^4.17.3", 65 | "@types/jest": "26.0.10", 66 | "@types/node": "^13.9.1", 67 | "@types/passport-jwt": "^3.0.3", 68 | "@types/passport-local": "^1.0.33", 69 | "@types/request-ip": "0.0.35", 70 | "@types/supertest": "^2.0.8", 71 | "@typescript-eslint/eslint-plugin": "3.9.1", 72 | "@typescript-eslint/parser": "^3.9.1", 73 | "eslint": "^7.24.0", 74 | "eslint-plugin-import": "^2.20.1", 75 | "jest": "26.4.2", 76 | "supertest": "^4.0.2", 77 | "ts-jest": "26.2.0", 78 | "ts-loader": "^6.2.1", 79 | "ts-node": "9.0.0", 80 | "tsconfig-paths": "^3.9.0", 81 | "typescript": "^3.7.4" 82 | }, 83 | "jest": { 84 | "moduleFileExtensions": [ 85 | "js", 86 | "json", 87 | "ts" 88 | ], 89 | "rootDir": "src", 90 | "testRegex": ".spec.ts$", 91 | "transform": { 92 | "^.+\\.(t|j)s$": "ts-jest" 93 | }, 94 | "coverageDirectory": "../coverage", 95 | "testEnvironment": "node" 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /scripts/secrets.js: -------------------------------------------------------------------------------- 1 | const crypto = require('crypto'); 2 | const fs = require('fs'); 3 | 4 | function secret(path) { 5 | const secret = crypto.randomBytes(20).toString('hex'); 6 | 7 | if (!fs.existsSync(path)) { 8 | fs.writeFileSync(path, secret); 9 | } 10 | } 11 | 12 | const secrets = [ 13 | './secrets/db_password.txt', 14 | './secrets/db_root_password.txt', 15 | './secrets/jwt_secret.txt', 16 | ] 17 | 18 | if (!fs.existsSync('./secrets')) { 19 | fs.mkdirSync('./secrets'); 20 | } 21 | 22 | secrets.forEach(secret); 23 | -------------------------------------------------------------------------------- /src/airport/airport-augmentation.entity.ts: -------------------------------------------------------------------------------- 1 | import { Column, Entity, Index, PrimaryGeneratedColumn } from 'typeorm'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | 4 | @Entity() 5 | export class AirportAugmentation { 6 | @PrimaryGeneratedColumn() 7 | @ApiProperty({ 8 | description: 'The unique identifier of the airport', 9 | example: '1234', 10 | }) 11 | id?: number; 12 | 13 | @Column({ default: '' }) 14 | @Index({ unique: true }) 15 | @ApiProperty({ description: 'The icao of the airport' }) 16 | icao: string; 17 | 18 | @Column({ default: -1 }) 19 | @ApiProperty({ description: 'The transition altitude of the airport' }) 20 | transAlt?: number; 21 | } 22 | -------------------------------------------------------------------------------- /src/airport/airport.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AirportController } from './airport.controller'; 3 | 4 | describe('AirportController', () => { 5 | let controller: AirportController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [AirportController] }).compile(); 9 | 10 | controller = module.get(AirportController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/airport/airport.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, CacheInterceptor, CacheTTL, Controller, Get, Param, Post, UseInterceptors } from '@nestjs/common'; 2 | import { ApiBody, ApiNotFoundResponse, ApiOkResponse, ApiParam, ApiTags } from '@nestjs/swagger'; 3 | import { AirportService } from './airport.service'; 4 | import { AirportBatchDto } from './dto/airport-batch.dto'; 5 | import { Airport } from './dto/airport.dto'; 6 | 7 | @ApiTags('Airport') 8 | @Controller('api/v1/airport') 9 | @UseInterceptors(CacheInterceptor) 10 | export class AirportController { 11 | constructor(private airport: AirportService) { 12 | } 13 | 14 | @Post('_batch') 15 | @ApiBody({ 16 | description: 'List of all ICAOs to fetch', 17 | type: AirportBatchDto, 18 | }) 19 | @ApiOkResponse({ description: 'List of found airports', type: [Airport] }) 20 | getBatch(@Body() body: AirportBatchDto): Promise { 21 | return this.airport.getBatch(body); 22 | } 23 | 24 | @Get(':icao') 25 | @CacheTTL(345600) 26 | @ApiParam({ name: 'icao', description: 'The ICAO of the airport to search for', example: 'KLAX' }) 27 | @ApiOkResponse({ description: 'Airport was found', type: Airport }) 28 | @ApiNotFoundResponse({ description: 'Airport was not found' }) 29 | getForICAO(@Param('icao') icao: string): Promise { 30 | return this.airport.getForICAO(icao); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/airport/airport.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpModule, Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { AirportService } from './airport.service'; 4 | import { AirportController } from './airport.controller'; 5 | import { AirportAugmentation } from './airport-augmentation.entity'; 6 | 7 | @Module({ 8 | imports: [ 9 | TypeOrmModule.forFeature([AirportAugmentation]), 10 | HttpModule, 11 | ], 12 | providers: [AirportService], 13 | controllers: [AirportController], 14 | }) 15 | export class AirportModule {} 16 | -------------------------------------------------------------------------------- /src/airport/airport.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AirportService } from './airport.service'; 3 | 4 | describe('AirportService', () => { 5 | let service: AirportService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [AirportService] }).compile(); 9 | 10 | service = module.get(AirportService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/airport/airport.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { InjectRepository } from '@nestjs/typeorm'; 3 | import { Repository } from 'typeorm'; 4 | import { AxiosResponse } from 'axios'; 5 | import { AirportAugmentation } from './airport-augmentation.entity'; 6 | import { CacheService } from '../cache/cache.service'; 7 | import { Airport } from './dto/airport.dto'; 8 | import { AirportBatchDto } from './dto/airport-batch.dto'; 9 | 10 | @Injectable() 11 | export class AirportService { 12 | private readonly logger = new Logger(AirportService.name); 13 | 14 | constructor(private readonly http: HttpService, 15 | @InjectRepository(AirportAugmentation) 16 | private readonly augmentation: Repository, 17 | private readonly cache: CacheService) { 18 | } 19 | 20 | async getForICAO(icao: string): Promise { 21 | const icaoCode = icao.toUpperCase(); 22 | this.logger.log(`Searching for ICAO '${icaoCode}'`); 23 | 24 | let response: AxiosResponse; 25 | 26 | const cacheHit = await this.cache.get(`/api/v1/airport/${icao}`); 27 | const cacheError = await this.cache.get(`upstream-error:/api/v1/airport/${icao}`); 28 | if (cacheError) { 29 | throw new HttpException(`Airport with ICAO '${icaoCode}' not found`, 404); 30 | } 31 | 32 | if (!cacheHit) { 33 | try { 34 | response = await this.http.get(`https://ourairportapi.com/airport/${icaoCode}?expand=false`).toPromise(); 35 | this.logger.debug(`Response status ${response.status} for airport request`); 36 | } catch (err) { 37 | this.logger.error(err); 38 | throw new HttpException(`Airport with ICAO '${icaoCode}' not found`, 404); 39 | } 40 | 41 | if (response.data.errorMessage || response.data.count > 1) { 42 | // Cache upstream 404s for 1 day 43 | this.cache.set(`upstream-error:/api/v1/airport/${icao}`, true, 86400).then(); // 1 day 44 | throw new HttpException(`Airport with ICAO '${icaoCode}' not found`, 404); 45 | } 46 | 47 | let augResult: AirportAugmentation | undefined; 48 | try { 49 | augResult = await this.augmentation.findOne({ icao }); 50 | } catch (_) { 51 | this.logger.debug(`Airport with ICAO '${icao}' has no augmentation`); 52 | } 53 | 54 | const [foundAirport] = response.data.results; 55 | const augmentedAirport = { 56 | icao: foundAirport.icao, 57 | iata: foundAirport.iata, 58 | type: foundAirport.type, 59 | name: foundAirport.name, 60 | lat: foundAirport.lat, 61 | lon: foundAirport.lon, 62 | elevation: foundAirport.elev || foundAirport.elevation, 63 | continent: foundAirport.continent, 64 | country: foundAirport.country, 65 | transAlt: augResult?.transAlt || NaN, 66 | }; 67 | this.cache.set(`/api/v1/airport/${icao}`, augmentedAirport, 345600).then(); // 4 days 68 | 69 | return augmentedAirport; 70 | } 71 | return cacheHit; 72 | } 73 | 74 | async getBatch(icaos: AirportBatchDto): Promise { 75 | const uniqueIcaos = [...new Set(icaos.icaos)]; 76 | 77 | // eslint-disable-next-line consistent-return 78 | const res = await Promise.all(uniqueIcaos.map(async (icao) => { 79 | try { 80 | return await this.getForICAO(icao); 81 | // eslint-disable-next-line no-empty 82 | } catch (_) {} 83 | })); 84 | 85 | return res.filter((arpt) => arpt !== undefined); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/airport/dto/airport-batch.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { IsNotEmpty } from 'class-validator'; 3 | 4 | export class AirportBatchDto { 5 | @IsNotEmpty() 6 | @ApiProperty({ description: 'The ICAOs to fetch', example: ['KLAX', 'KSFO'] }) 7 | icaos: string[]; 8 | } 9 | -------------------------------------------------------------------------------- /src/airport/dto/airport.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class Airport { 4 | @ApiProperty({ description: 'The airport ICAO', example: 'KLAX' }) 5 | icao: string; 6 | 7 | @ApiProperty({ description: 'The airport IATA', example: 'LAX' }) 8 | iata: string; 9 | 10 | @ApiProperty({ description: 'The type of the airport', enum: ['large_airport', 'medium_airport', 'small_airport'] }) 11 | type: string; 12 | 13 | @ApiProperty({ description: 'The name of the airport', example: 'Los Angeles International Airport' }) 14 | name: string; 15 | 16 | @ApiProperty({ description: 'The latitude of the airport', example: 33.94250107 }) 17 | lat: number; 18 | 19 | @ApiProperty({ description: 'The longitude of the airport', example: -118.4079971 }) 20 | lon: number; 21 | 22 | @ApiProperty({ description: 'The elevation of the airport', example: 125 }) 23 | elevation: number; 24 | 25 | @ApiProperty({ description: 'The continent the airport is in', example: 'NA' }) 26 | continent: string; 27 | 28 | @ApiProperty({ description: 'The country the airport is in', example: 'US' }) 29 | country: string; 30 | 31 | @ApiProperty({ description: 'The transition altitude of the airport', example: 18000 }) 32 | transAlt: number; 33 | } 34 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get, Redirect } from '@nestjs/common'; 2 | 3 | @Controller() 4 | export class AppController { 5 | @Get() 6 | @Redirect('/api/#', 301) 7 | documentation() { 8 | 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpModule, Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { ConfigModule, ConfigService } from '@nestjs/config'; 4 | import { ScheduleModule } from '@nestjs/schedule'; 5 | import { WinstonModule } from 'nest-winston'; 6 | import * as winston from 'winston'; 7 | import { APP_FILTER } from '@nestjs/core'; 8 | import { AppController } from './app.controller'; 9 | import { MetarController } from './metar/metar.controller'; 10 | import { MetarService } from './metar/metar.service'; 11 | import { AtisController } from './atis/atis.controller'; 12 | import { AtisService } from './atis/atis.service'; 13 | import { TelexModule } from './telex/telex.module'; 14 | import { TafController } from './taf/taf.controller'; 15 | import { TafService } from './taf/taf.service'; 16 | import configuration from './config/configuration'; 17 | import { FbwNamingStrategy } from './utilities/db-naming'; 18 | import { CacheModule } from './cache/cache.module'; 19 | import { HealthModule } from './health/health.module'; 20 | import { AirportModule } from './airport/airport.module'; 21 | import { GitVersionsModule } from './git-versions/git-versions.module'; 22 | import { ChartsModule } from './charts/charts.module'; 23 | import { AtcController } from './atc/atc.controller'; 24 | import { VatsimService } from './utilities/vatsim.service'; 25 | import { AtcService } from './atc/atc.service'; 26 | import { IvaoService } from './utilities/ivao.service'; 27 | import { GnssModule } from './gnss/gnss.module'; 28 | import { CpdlcController } from './cpdlc/cpdlc.controller'; 29 | import { CpdlcService } from './cpdlc/cpdlc.service'; 30 | import { NotFoundExceptionFilter } from './utilities/not-found.filter'; 31 | 32 | @Module({ 33 | imports: [ 34 | TypeOrmModule.forRootAsync({ 35 | imports: [ConfigModule], 36 | inject: [ConfigService], 37 | useFactory: (configService: ConfigService) => { 38 | const masterHost = configService.get('database.host'); 39 | const username = configService.get('database.username'); 40 | const password = configService.get('database.password'); 41 | const database = configService.get('database.database'); 42 | const port = configService.get('database.port'); 43 | const replicas = configService.get('database.replicas').split(';').filter((x) => x !== ''); 44 | 45 | if (replicas.length > 0) { 46 | return { 47 | type: 'mysql', 48 | replication: { 49 | master: { 50 | host: masterHost, 51 | port, 52 | username, 53 | password, 54 | database, 55 | }, 56 | slaves: replicas.map((replica) => ({ 57 | host: replica, 58 | port, 59 | username, 60 | password, 61 | database, 62 | })), 63 | }, 64 | autoLoadEntities: true, 65 | synchronize: true, 66 | legacySpatialSupport: false, 67 | namingStrategy: new FbwNamingStrategy(), 68 | logging: configService.get('database.logging'), 69 | extra: { connectionLimit: configService.get('database.connectionLimit') }, 70 | }; 71 | } 72 | 73 | return { 74 | type: 'mysql', 75 | host: masterHost, 76 | port, 77 | username, 78 | password, 79 | database, 80 | autoLoadEntities: true, 81 | synchronize: true, 82 | legacySpatialSupport: false, 83 | namingStrategy: new FbwNamingStrategy(), 84 | logging: configService.get('database.logging'), 85 | extra: { connectionLimit: configService.get('database.connectionLimit') }, 86 | }; 87 | }, 88 | }), 89 | ConfigModule.forRoot({ 90 | isGlobal: true, 91 | load: [configuration], 92 | }), 93 | ScheduleModule.forRoot(), 94 | WinstonModule.forRootAsync({ 95 | imports: [ConfigService], 96 | inject: [ConfigService], 97 | useFactory: (configService: ConfigService) => ({ 98 | levels: { 99 | error: 0, 100 | warn: 1, 101 | info: 2, 102 | debug: 3, 103 | verbose: 4, 104 | }, 105 | level: configService.get('logger.level'), 106 | format: configService.get('logger.format'), 107 | transports: [ 108 | new winston.transports.Console(), 109 | ], 110 | }), 111 | }), 112 | TelexModule, 113 | HttpModule, 114 | CacheModule, 115 | HealthModule, 116 | AirportModule, 117 | GitVersionsModule, 118 | ChartsModule, 119 | GnssModule, 120 | ], 121 | controllers: [ 122 | AppController, 123 | MetarController, 124 | AtisController, 125 | TafController, 126 | AtcController, 127 | CpdlcController, 128 | ], 129 | providers: [ 130 | { 131 | provide: APP_FILTER, 132 | useClass: NotFoundExceptionFilter, 133 | }, 134 | MetarService, AtisService, TafService, VatsimService, IvaoService, AtcService, CpdlcService], 135 | }) 136 | export class AppModule { 137 | } 138 | -------------------------------------------------------------------------------- /src/atc/atc-info.class.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export enum AtcType { 4 | UNKNOWN, 5 | DELIVERY, 6 | GROUND, 7 | TOWER, 8 | DEPARTURE, 9 | APPROACH, 10 | RADAR, 11 | ATIS 12 | } 13 | 14 | export class ATCInfo { 15 | @ApiProperty({ description: 'The atc callsign', example: 'EBBR_TWR' }) 16 | callsign: string; 17 | 18 | @ApiProperty({ description: 'The atc frequency', example: '128.800' }) 19 | frequency: string; 20 | 21 | @ApiProperty({ description: 'The atc visual range', example: 150 }) 22 | visualRange: number; 23 | 24 | @ApiProperty({ description: 'The atc current ATIS', example: ['line 1', 'line2', 'line3'] }) 25 | textAtis: string[]; 26 | 27 | @ApiProperty({ description: 'The atc type', example: 'GND' }) 28 | type: AtcType; 29 | 30 | @ApiProperty({ description: 'The atc latitude', example: 32.08420727935125 }) 31 | latitude?: number; 32 | 33 | @ApiProperty({ description: 'The atc longitude', example: -81.14929543157402 }) 34 | longitude?: number; 35 | } 36 | -------------------------------------------------------------------------------- /src/atc/atc.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CacheInterceptor, 3 | CacheTTL, 4 | Controller, 5 | Get, 6 | Query, 7 | UseInterceptors, 8 | } from '@nestjs/common'; 9 | import { 10 | ApiOkResponse, 11 | ApiQuery, 12 | ApiTags, 13 | } from '@nestjs/swagger'; 14 | import { ATCInfo } from './atc-info.class'; 15 | import { AtcService } from './atc.service'; 16 | 17 | @ApiTags('ATC') 18 | @Controller('api/v1/atc') 19 | @UseInterceptors(CacheInterceptor) 20 | export class AtcController { 21 | constructor(private atcService: AtcService) {} 22 | 23 | @Get('') 24 | @CacheTTL(120) 25 | @ApiQuery({ 26 | name: 'source', 27 | description: 'The source for the atcs', 28 | example: 'vatsim', 29 | required: true, 30 | enum: ['vatsim', 'ivao'], 31 | }) 32 | @ApiOkResponse({ description: 'list of connected atc', type: [ATCInfo] }) 33 | async getControllers(@Query('source') source?: string): Promise { 34 | if (source === 'vatsim') { 35 | return this.atcService.getVatsimControllers(); 36 | } 37 | if (source === 'ivao') { 38 | return this.atcService.getIvaoControllers(); 39 | } 40 | return null; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/atc/atc.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { ATCInfo, AtcType } from './atc-info.class'; 3 | import { VatsimService } from '../utilities/vatsim.service'; 4 | import { IvaoService } from '../utilities/ivao.service'; 5 | 6 | @Injectable() 7 | export class AtcService { 8 | constructor(private readonly vatsimService: VatsimService, 9 | private readonly ivaoService: IvaoService) { } 10 | 11 | public async getVatsimControllers(): Promise { 12 | const data = await this.vatsimService.fetchVatsimData(); 13 | const transceivers = await this.vatsimService.fetchVatsimTransceivers(); 14 | 15 | const arr: ATCInfo[] = []; 16 | for (const c of [...data.controllers, ...data.atis]) { 17 | const atcType = this.callSignToAtcType(c.callsign); 18 | if (atcType !== AtcType.UNKNOWN) { 19 | const trans = transceivers.find((t) => t.callsign === c.callsign); 20 | const position = this.getCenterOfCoordinates(trans?.transceivers); 21 | const freqency = trans ? this.getFrequency(trans?.transceivers) : c.frequency; 22 | 23 | if (freqency) { 24 | arr.push({ 25 | callsign: c.callsign, 26 | frequency: freqency, 27 | textAtis: c.text_atis, 28 | visualRange: c.visual_range, 29 | type: this.callSignToAtcType(c.callsign), 30 | latitude: position ? position[0] : null, 31 | longitude: position ? position[1] : null, 32 | }); 33 | } 34 | } 35 | } 36 | 37 | // try to force ATIS location 38 | for (const c of arr.filter((i) => i.type === AtcType.ATIS && (!i.latitude || !i.longitude))) { 39 | const other = arr.find((o) => o.callsign.split('_')[0] === c.callsign.split('_')[0]); 40 | if (other) { 41 | c.latitude = other.latitude; 42 | c.longitude = other.longitude; 43 | } 44 | } 45 | return arr; 46 | } 47 | 48 | public async getIvaoControllers(): Promise { 49 | const { clients: { atcs } } = await this.ivaoService.fetchIvaoData(); 50 | 51 | return atcs.map((atc) => ({ 52 | callsign: atc.callsign, 53 | frequency: atc.atcSession.frequency.toString(), 54 | textAtis: atc.atis?.lines, 55 | latitude: atc.lastTrack.latitude, 56 | longitude: atc.lastTrack.longitude, 57 | type: this.callSignToAtcType(atc.callsign), 58 | // TODO FIXME: visual range is not currently available in the new IVAO Whazzup v2 data 59 | visualRange: 100, 60 | })); 61 | } 62 | 63 | public callSignToAtcType(callsign: string): AtcType { 64 | switch (callsign.split('_').reverse()[0]) { 65 | case 'CTR': return AtcType.RADAR; 66 | case 'DEL': return AtcType.DELIVERY; 67 | case 'GND': return AtcType.GROUND; 68 | case 'DEP': return AtcType.DEPARTURE; 69 | case 'TWR': return AtcType.TOWER; 70 | case 'APP': return AtcType.APPROACH; 71 | case 'ATIS': return AtcType.ATIS; 72 | default: return AtcType.UNKNOWN; 73 | } 74 | } 75 | 76 | public getFrequency(array: any[]): string { 77 | if (array && array.length > 0 && array[0].frequency) { 78 | let freqInString: string = array[0].frequency.toString(); 79 | freqInString = `${freqInString.substr(0, 3)}.${freqInString.substr(3)}`; 80 | return parseFloat(freqInString).toFixed(3); 81 | } 82 | return null; 83 | } 84 | 85 | public getCenterOfCoordinates(array: any[]) { 86 | if (!array) { 87 | return null; 88 | } 89 | 90 | const numCoords = array.length; 91 | if (numCoords === 1) { 92 | return [array[0].latDeg, array[0].lonDeg]; 93 | } 94 | 95 | let X = 0.0; 96 | let Y = 0.0; 97 | let Z = 0.0; 98 | 99 | for (let i = 0; i < numCoords; i++) { 100 | const lat = (array[i].latDeg * Math.PI) / 180; 101 | const lon = (array[i].lonDeg * Math.PI) / 180; 102 | const a = Math.cos(lat) * Math.cos(lon); 103 | const b = Math.cos(lat) * Math.sin(lon); 104 | const c = Math.sin(lat); 105 | 106 | X += a; 107 | Y += b; 108 | Z += c; 109 | } 110 | 111 | X /= numCoords; 112 | Y /= numCoords; 113 | Z /= numCoords; 114 | 115 | const lon = Math.atan2(Y, X); 116 | const hyp = Math.sqrt(X * X + Y * Y); 117 | const lat = Math.atan2(Z, hyp); 118 | 119 | const finalLat = (lat * 180) / Math.PI; 120 | const finalLng = (lon * 180) / Math.PI; 121 | 122 | return [finalLat, finalLng]; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /src/atis/atis.class.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class Atis { 4 | @ApiProperty({ description: 'The airport ICAO', example: 'KLAX' }) 5 | icao: string; 6 | 7 | @ApiProperty({ description: 'The source of the ATIS notice', enum: ['faa', 'vatsim', 'ivao', 'pilotedge'] }) 8 | source: string; 9 | 10 | @ApiProperty({ 11 | description: 'The combined ATIS notice', 12 | example: 'KLAX ATIS INFO V 2253Z. 25012KT 10SM FEW025 SCT043 BKN240 20/12 A2993 (TWO NINER NINER THREE). ' 13 | + 'SIMUL ILS APPS IN PROG RWYS 24R AND 25L, OR VCTR FOR VIS APP WILL BE PROVIDED. SIMUL VIS APPS TO ALL RWYS ' 14 | + 'ARE IN PROG. PARALLEL APPS IN PROG BTWN LOS ANGELES AND HAWTHORNE ARPTS. SIMUL INSTRUMENT DEPS IN PROG ' 15 | + 'RWYS 24 AND 25. NOTAMS... ASDE-X SYSTEM IN USE. ACTIVATE TRANSPONDER WITH MODE C ON ALL TWYS AND RWYS.' 16 | + ' READBACK ALL RWY HOLD SHORT INSTRUCTIONS. ...ADVS YOU HAVE INFO V.', 17 | }) 18 | combined?: string; 19 | 20 | @ApiProperty({ description: 'The arrival ATIS notice' }) 21 | arr?: string; 22 | 23 | @ApiProperty({ description: 'The departure ATIS notice' }) 24 | dep?: string; 25 | } 26 | -------------------------------------------------------------------------------- /src/atis/atis.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AtisController } from './atis.controller'; 3 | 4 | describe('AtisController', () => { 5 | let controller: AtisController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [AtisController] }).compile(); 9 | 10 | controller = module.get(AtisController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/atis/atis.controller.ts: -------------------------------------------------------------------------------- 1 | import { CacheInterceptor, CacheTTL, Controller, Get, Param, Query, UseInterceptors } from '@nestjs/common'; 2 | import { ApiNotFoundResponse, ApiOkResponse, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'; 3 | import { AtisService } from './atis.service'; 4 | import { Atis } from './atis.class'; 5 | 6 | @ApiTags('ATIS') 7 | @Controller('atis') 8 | @UseInterceptors(CacheInterceptor) 9 | export class AtisController { 10 | constructor(private atis: AtisService) { 11 | } 12 | 13 | @Get(':icao') 14 | @CacheTTL(120) 15 | @ApiParam({ name: 'icao', description: 'The ICAO of the airport to search for', example: 'KLAX' }) 16 | @ApiQuery({ 17 | name: 'source', 18 | description: 'The source for the ICAO', 19 | example: 'faa', 20 | required: false, 21 | enum: ['faa', 'vatsim', 'ivao', 'pilotedge'], 22 | }) 23 | @ApiOkResponse({ description: 'ATIS notice was found', type: Atis }) 24 | @ApiNotFoundResponse({ description: 'ATIS not available for ICAO' }) 25 | getForICAO(@Param('icao') icao: string, @Query('source') source?: string): Promise { 26 | return this.atis.getForICAO(icao, source); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/atis/atis.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AtisService } from './atis.service'; 3 | 4 | describe('AtisService', () => { 5 | let service: AtisService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [AtisService] }).compile(); 9 | 10 | service = module.get(AtisService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/atis/atis.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { Observable } from 'rxjs'; 3 | import { catchError, map, tap } from 'rxjs/operators'; 4 | import { Atis } from './atis.class'; 5 | import { CacheService } from '../cache/cache.service'; 6 | import { VatsimService } from '../utilities/vatsim.service'; 7 | import { IvaoService } from '../utilities/ivao.service'; 8 | 9 | @Injectable() 10 | export class AtisService { 11 | private readonly logger = new Logger(AtisService.name); 12 | 13 | constructor( 14 | private http: HttpService, 15 | private readonly cache: CacheService, 16 | private readonly vatsim: VatsimService, 17 | private readonly ivao: IvaoService, 18 | ) {} 19 | 20 | getForICAO(icao: string, source?: string): Promise { 21 | const icaoCode = icao.toUpperCase(); 22 | this.logger.debug( 23 | `Searching for ICAO ${icaoCode} from source ${source}`, 24 | ); 25 | 26 | switch (source?.toLowerCase()) { 27 | case 'faa': 28 | default: 29 | return this.handleFaa(icaoCode).toPromise(); 30 | case 'vatsim': 31 | return this.handleVatsim(icaoCode); 32 | case 'ivao': 33 | return this.handleIvao(icaoCode); 34 | case 'pilotedge': 35 | return this.handlePilotEdge(icaoCode).toPromise(); 36 | } 37 | } 38 | 39 | // FAA 40 | private handleFaa(icao: string): Observable { 41 | return this.http.get(`https://datis.clowd.io/api/${icao}`).pipe( 42 | tap((response) => this.logger.debug( 43 | `Response status ${response.status} for FAA ATIS request`, 44 | )), 45 | map((response) => { 46 | if (response.data.error) { 47 | throw this.generateNotAvailableException( 48 | response.data, 49 | icao, 50 | ); 51 | } 52 | 53 | const atis: Atis = { 54 | icao, 55 | source: 'FAA', 56 | }; 57 | 58 | response.data.forEach((x) => { 59 | atis[x.type] = x.datis; 60 | }); 61 | 62 | atis.dep?.toUpperCase(); 63 | atis.arr?.toUpperCase(); 64 | atis.combined?.toUpperCase(); 65 | 66 | return atis; 67 | }), 68 | catchError((err) => { 69 | throw this.generateNotAvailableException(err, icao); 70 | }), 71 | ); 72 | } 73 | 74 | private handleVatsim(icao: string): Promise { 75 | return this.vatsim 76 | .fetchVatsimData() 77 | .then((response) => { 78 | const combined = response.atis.find((x) => x.callsign === `${icao}_ATIS`)?.text_atis.join(' ').toUpperCase(); 79 | const arr = response.atis.find((x) => x.callsign === `${icao}_A_ATIS`)?.text_atis.join(' ').toUpperCase(); 80 | const dep = response.atis.find((x) => x.callsign === `${icao}_D_ATIS`)?.text_atis.join(' ').toUpperCase(); 81 | 82 | if (combined === undefined && arr === undefined && dep === undefined) { 83 | throw new Error('No ATIS found'); 84 | } 85 | 86 | return { 87 | icao, 88 | source: 'Vatsim', 89 | combined, 90 | arr, 91 | dep, 92 | }; 93 | }) 94 | .catch((e) => { 95 | throw this.generateNotAvailableException(e, icao); 96 | }); 97 | } 98 | 99 | private handleIvao(icao: string): Promise { 100 | return this.ivao 101 | .fetchIvaoData() 102 | .then((response) => ({ 103 | icao, 104 | source: 'IVAO', 105 | combined: response.clients.atcs 106 | .find((atc) => atc.callsign.includes(icao.toUpperCase())) 107 | ?.atis?.lines.join(' '), 108 | })) 109 | .catch((e) => { 110 | throw this.generateNotAvailableException(e, icao); 111 | }); 112 | } 113 | 114 | // PilotEdge 115 | private handlePilotEdge(icao: string): Observable { 116 | return this.http 117 | .get(`https://www.pilotedge.net/atis/${icao}.json`) 118 | .pipe( 119 | tap((response) => this.logger.debug( 120 | `Response status ${response.status} for PilotEdge ATIS request`, 121 | )), 122 | map((response) => ({ 123 | icao, 124 | source: 'FAA', 125 | combined: response.data.text 126 | .replace('\n\n', ' ') 127 | .toUpperCase(), 128 | })), 129 | catchError((err) => { 130 | throw this.generateNotAvailableException(err, icao); 131 | }), 132 | ); 133 | } 134 | 135 | private generateNotAvailableException(err: any, icao: string) { 136 | const exception = new HttpException( 137 | `ATIS not available for ICAO: ${icao}`, 138 | 404, 139 | ); 140 | this.logger.error(err); 141 | this.logger.error(exception); 142 | return exception; 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/auth/auth.module.ts: -------------------------------------------------------------------------------- 1 | import { Logger, Module } from '@nestjs/common'; 2 | import { PassportModule } from '@nestjs/passport'; 3 | import { JwtModule } from '@nestjs/jwt'; 4 | import { ConfigModule, ConfigService } from '@nestjs/config'; 5 | import { FlightStrategy } from './flights/flight.strategy'; 6 | import { AuthService } from './auth.service'; 7 | 8 | @Module({ 9 | imports: [ 10 | ConfigService, 11 | PassportModule, 12 | JwtModule.registerAsync({ 13 | imports: [ConfigModule], 14 | useFactory: async (configService: ConfigService) => ({ 15 | secret: configService.get('auth.secret'), 16 | signOptions: { expiresIn: configService.get('auth.expires') }, 17 | }), 18 | inject: [ConfigService], 19 | }), 20 | ], 21 | providers: [AuthService, FlightStrategy], 22 | exports: [AuthService], 23 | }) 24 | export class AuthModule { 25 | private readonly logger = new Logger(AuthModule.name); 26 | 27 | constructor(private readonly configService: ConfigService) { 28 | if (configService.get('auth.secret') === 'FlyByWire') { 29 | this.logger.error('Use a JWT secret in production mode'); 30 | process.exit(99); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/auth/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AuthService } from './auth.service'; 3 | 4 | describe('AuthService', () => { 5 | let service: AuthService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [AuthService] }).compile(); 9 | 10 | service = module.get(AuthService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/auth/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { JwtService } from '@nestjs/jwt'; 3 | import { FlightToken } from './flights/flight-token.class'; 4 | 5 | @Injectable() 6 | export class AuthService { 7 | constructor( 8 | private jwtService: JwtService, 9 | ) {} 10 | 11 | registerFlight(flight: string, connectionId: string): FlightToken { 12 | const payload = { flight, sub: connectionId }; 13 | return { 14 | accessToken: this.jwtService.sign(payload), 15 | flight, 16 | connection: connectionId, 17 | }; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/auth/flights/flight-auth-guard.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { AuthGuard } from '@nestjs/passport'; 3 | 4 | @Injectable() 5 | export class FlightAuthGuard extends AuthGuard('flight') {} 6 | -------------------------------------------------------------------------------- /src/auth/flights/flight-auth.guard.spec.ts: -------------------------------------------------------------------------------- 1 | import { FlightAuthGuard } from './flight-auth-guard.service'; 2 | 3 | describe('FlightAuthGuard', () => { 4 | it('should be defined', () => { 5 | expect(new FlightAuthGuard()).toBeDefined(); 6 | }); 7 | }); 8 | -------------------------------------------------------------------------------- /src/auth/flights/flight-token.class.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class FlightToken { 4 | @ApiProperty({ description: 'The access token for secured endpoints' }) 5 | accessToken: string; 6 | 7 | @ApiProperty({ description: 'The connection ID the token refers to', example: '2a883a5c-b1f3-4a16-9fa4-b10515742d63' }) 8 | connection: string; 9 | 10 | @ApiProperty({ description: 'The flight number the token refers to', example: 'OS 41' }) 11 | flight: string; 12 | } 13 | -------------------------------------------------------------------------------- /src/auth/flights/flight.strategy.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | import { PassportStrategy } from '@nestjs/passport'; 3 | import { ExtractJwt, Strategy } from 'passport-jwt'; 4 | import { ConfigService } from '@nestjs/config'; 5 | 6 | @Injectable() 7 | export class FlightStrategy extends PassportStrategy(Strategy, 'flight') { 8 | constructor(private readonly configService: ConfigService) { 9 | super({ 10 | jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 11 | ignoreExpiration: false, 12 | secretOrKey: configService.get('auth.secret'), 13 | }); 14 | } 15 | 16 | validate(payload: any) { 17 | return { connectionId: payload.sub, flight: payload.flight }; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/cache/cache.module.ts: -------------------------------------------------------------------------------- 1 | import * as redisStore from 'cache-manager-redis-store'; 2 | import { CacheModule as NestCache, Global, Module } from '@nestjs/common'; 3 | import { ConfigModule, ConfigService } from '@nestjs/config'; 4 | import { CacheService } from './cache.service'; 5 | 6 | @Global() 7 | @Module({ 8 | imports: [ 9 | NestCache.registerAsync({ 10 | imports: [ConfigModule], 11 | inject: [ConfigService], 12 | useFactory: async (configService: ConfigService) => ({ 13 | store: redisStore, 14 | host: configService.get('redis.host'), 15 | port: configService.get('redis.port'), 16 | }), 17 | }), 18 | ], 19 | providers: [ 20 | CacheService, 21 | ], 22 | exports: [ 23 | NestCache, 24 | CacheService, 25 | ], 26 | }) 27 | export class CacheModule {} 28 | -------------------------------------------------------------------------------- /src/cache/cache.service.ts: -------------------------------------------------------------------------------- 1 | import { CACHE_MANAGER, Inject, Injectable } from '@nestjs/common'; 2 | import { Cache } from 'cache-manager'; 3 | 4 | @Injectable() 5 | export class CacheService { 6 | constructor(@Inject(CACHE_MANAGER) private readonly cacheManager: Cache) {} 7 | 8 | public get(key: string): Promise { 9 | return this.cacheManager.get(key); 10 | } 11 | 12 | public set(key: string, value: any, ttl: number): Promise { 13 | return this.cacheManager.set(key, value, { ttl }); 14 | } 15 | 16 | public del(key: string): Promise { 17 | return this.cacheManager.del(key); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/charts/charts.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { ChartsController } from './charts.controller'; 3 | 4 | describe('ChartsController', () => { 5 | let controller: ChartsController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [ChartsController] }).compile(); 9 | 10 | controller = module.get(ChartsController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/charts/charts.controller.ts: -------------------------------------------------------------------------------- 1 | import { CacheInterceptor, CacheTTL, Controller, Get, Param, UseInterceptors } from '@nestjs/common'; 2 | import { ApiNotFoundResponse, ApiOkResponse, ApiParam, ApiTags } from '@nestjs/swagger'; 3 | import { Observable } from 'rxjs'; 4 | import { ChartsService } from './charts.service'; 5 | import { Charts } from './dto/charts.dto'; 6 | 7 | @ApiTags('Charts') 8 | @Controller('api/v1/charts') 9 | @UseInterceptors(CacheInterceptor) 10 | export class ChartsController { 11 | constructor(private charts: ChartsService) { 12 | } 13 | 14 | @Get(':icao') 15 | @CacheTTL(3600) 16 | @ApiParam({ name: 'icao', description: 'The ICAO of the airport to search for', example: 'KLAX' }) 17 | @ApiOkResponse({ description: 'Charts were found', type: Charts }) 18 | @ApiNotFoundResponse({ description: 'Charts not available for ICAO' }) 19 | getForICAO(@Param('icao') icao: string): Observable { 20 | return this.charts.getForICAO(icao); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/charts/charts.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpModule, Module } from '@nestjs/common'; 2 | import { ChartsController } from './charts.controller'; 3 | import { ChartsService } from './charts.service'; 4 | 5 | @Module({ 6 | imports: [HttpModule], 7 | providers: [ChartsService], 8 | controllers: [ChartsController], 9 | }) 10 | export class ChartsModule {} 11 | -------------------------------------------------------------------------------- /src/charts/charts.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { ChartsService } from './charts.service'; 3 | 4 | describe('ChartsService', () => { 5 | let service: ChartsService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [ChartsService] }).compile(); 9 | 10 | service = module.get(ChartsService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/charts/charts.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { Observable } from 'rxjs'; 3 | import { catchError, map, tap } from 'rxjs/operators'; 4 | import { Charts } from './dto/charts.dto'; 5 | 6 | @Injectable() 7 | export class ChartsService { 8 | private readonly logger = new Logger(ChartsService.name); 9 | 10 | constructor(private http: HttpService) { 11 | } 12 | 13 | getForICAO(icao: string): Observable { 14 | const icaoCode = icao.toUpperCase(); 15 | this.logger.debug(`Searching for ICAO ${icaoCode}`); 16 | 17 | return this.handleFaa(icaoCode); 18 | } 19 | 20 | // FAA 21 | private handleFaa(icao: string): Observable { 22 | return this.http.get(`https://nfdc.faa.gov/nfdcApps/services/ajv5/airportDisplay.jsp?airportId=${icao}`) 23 | .pipe( 24 | tap((response) => this.logger.debug(`Response status ${response.status} for FAA charts request`)), 25 | map((response) => { 26 | if (response.data.error) { 27 | throw this.generateNotAvailableException(response.data, icao); 28 | } 29 | 30 | const regexp = /<\/i> (.+)<\/a><\/span>/g; 31 | const matches = [...response.data.matchAll(regexp)]; 32 | 33 | return { 34 | icao, 35 | charts: matches.map((x) => ({ url: x[1], name: x[2] })), 36 | }; 37 | }), 38 | catchError( 39 | (err) => { 40 | throw this.generateNotAvailableException(err, icao); 41 | }, 42 | ), 43 | ); 44 | } 45 | 46 | private generateNotAvailableException(err: any, icao: string) { 47 | const exception = new HttpException(`Charts not available for ICAO: ${icao}`, 404); 48 | this.logger.error(err); 49 | this.logger.error(exception); 50 | return exception; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/charts/dto/chart.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class Chart { 4 | @ApiProperty({ description: 'The chart URL', example: 'http://aeronav.faa.gov/d-tpp/2101/00237AD.PDF' }) 5 | url: string; 6 | 7 | @ApiProperty({ description: 'The chart name', example: 'AIRPORT DIAGRAM for LAX' }) 8 | name: string; 9 | } 10 | -------------------------------------------------------------------------------- /src/charts/dto/charts.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { Chart } from './chart.dto'; 3 | 4 | export class Charts { 5 | @ApiProperty({ description: 'The airport ICAO', example: 'KLAX' }) 6 | icao: string; 7 | 8 | @ApiProperty({ description: 'The list of chart URLs', type: Chart }) 9 | charts?: Chart[]; 10 | } 11 | -------------------------------------------------------------------------------- /src/common/Bounds.ts: -------------------------------------------------------------------------------- 1 | import { Type } from 'class-transformer'; 2 | import { Max, Min } from 'class-validator'; 3 | 4 | export class BoundsDto { 5 | @Type(() => Number) 6 | @Min(-90) 7 | @Max(90) 8 | north = 90; 9 | 10 | @Type(() => Number) 11 | @Min(-180) 12 | @Max(180) 13 | east = 180; 14 | 15 | @Type(() => Number) 16 | @Min(-90) 17 | @Max(90) 18 | south = -90; 19 | 20 | @Type(() => Number) 21 | @Min(-180) 22 | @Max(180) 23 | west = -180; 24 | } 25 | -------------------------------------------------------------------------------- /src/common/Pagination.ts: -------------------------------------------------------------------------------- 1 | import { Type } from 'class-transformer'; 2 | import { IsInt, IsPositive, Max, Min } from 'class-validator'; 3 | 4 | export class PaginationDto { 5 | @Type(() => Number) 6 | @IsPositive() 7 | @IsInt() 8 | @Max(100) 9 | take = 25; 10 | 11 | @Type(() => Number) 12 | @Min(0) 13 | @IsInt() 14 | skip = 0; 15 | } 16 | -------------------------------------------------------------------------------- /src/config/configuration.ts: -------------------------------------------------------------------------------- 1 | import * as fs from 'fs'; 2 | import { utilities as nestWinstonModuleUtilities } from 'nest-winston'; 3 | import * as winston from 'winston'; 4 | 5 | export default () => ({ 6 | logger: { 7 | level: process.env.LOGGER_LEVEL || 'debug', 8 | format: getLoggingFormat(process.env.LOGGER_FORMAT), 9 | }, 10 | database: { 11 | host: process.env.DATABASE_HOST || 'localhost', 12 | port: parseInt(process.env.DATABASE_PORT) || 3306, 13 | database: process.env.DATABASE_DATABASE || 'fbw', 14 | username: process.env.DATABASE_USERNAME || 'fbw', 15 | password: envOrFile('DATABASE_PASSWORD', './secrets/db_password.txt'), 16 | logging: process.env.DATABASE_LOGGING || 'error', 17 | connectionLimit: parseInt(process.env.DATABASE_CONN_LIMIT) || 10, 18 | replicas: process.env.DATABASE_READ_ONLY_HOSTS || '', 19 | }, 20 | redis: { 21 | host: process.env.REDIS_HOST || 'localhost', 22 | port: parseInt(process.env.REDIS_PORT) || 6379, 23 | }, 24 | telex: { 25 | disableCleanup: envBool('TELEX_DISABLE_CLEANUP', true), 26 | timeoutMin: parseInt(process.env.TELEX_TIMEOUT_MIN) || 6, 27 | discordWebhook: process.env.TELEX_DISCORD_WEBHOOK || '', 28 | }, 29 | auth: { 30 | secret: envOrFile('AUTH_SECRET', './secrets/jwt_secret.txt') || 'FlyByWire', 31 | expires: process.env.AUTH_EXPIRES || '12h', 32 | }, 33 | github: { token: envOrFile('GITHUB_TOKEN', './secrets/github_token.txt') || '' }, 34 | }); 35 | 36 | function envOrFile(envName: string, defaultPath?: string): string { 37 | if (process.env[envName]) { 38 | return process.env[envName]; 39 | } 40 | 41 | if (process.env[`${envName}_FILE`]) { 42 | return fs.readFileSync(process.env[`${envName}_FILE`]).toString().trim(); 43 | } 44 | 45 | if (defaultPath && fs.existsSync(defaultPath)) { 46 | return fs.readFileSync(defaultPath).toString().trim(); 47 | } 48 | 49 | return ''; 50 | } 51 | 52 | function envBool(envName: string, defaultValue: boolean): boolean { 53 | if (process.env[envName]) { 54 | return process.env[envName].toLowerCase() === 'true'; 55 | } 56 | 57 | return defaultValue; 58 | } 59 | 60 | function getLoggingFormat(env: string) { 61 | switch (env) { 62 | case 'json': 63 | default: 64 | return winston.format.json(); 65 | case 'splat': 66 | return winston.format.splat(); 67 | case 'nest': 68 | return nestWinstonModuleUtilities.format.nestLike(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/cpdlc/cpdlc.class.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class Cpdlc { 4 | @ApiProperty({ description: 'The server\'s response', example: 'ok {}', }) 5 | response: string; 6 | } 7 | -------------------------------------------------------------------------------- /src/cpdlc/cpdlc.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { CpdlcController } from './cpdlc.controller'; 3 | 4 | describe('CpdlcController', () => { 5 | let controller: CpdlcController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [CpdlcController] }).compile(); 9 | 10 | controller = module.get(CpdlcController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/cpdlc/cpdlc.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Post } from '@nestjs/common'; 2 | import { 3 | ApiBody, 4 | ApiCreatedResponse, 5 | ApiNotFoundResponse, 6 | ApiTags, 7 | } from '@nestjs/swagger'; 8 | import { CpdlcService } from './cpdlc.service'; 9 | import { CpdlcMessageDto } from './dto/cpdlc-message.dto'; 10 | import { Cpdlc } from './cpdlc.class'; 11 | 12 | @ApiTags('HOPPIE') 13 | @Controller('api/v1/hoppie') 14 | export class CpdlcController { 15 | constructor(private cpdlc: CpdlcService) { 16 | } 17 | 18 | @Post() 19 | @ApiBody({ description: 'The message to send', type: CpdlcMessageDto }) 20 | @ApiCreatedResponse({ description: 'The message could be addressed', type: Cpdlc }) 21 | @ApiNotFoundResponse({ description: 'The sender or recipient flight number could not be found' }) 22 | async requestData(@Body() body: CpdlcMessageDto): Promise { 23 | return this.cpdlc.getData(body); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/cpdlc/cpdlc.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { CpdlcService } from './cpdlc.service'; 3 | 4 | describe('CpdlcService', () => { 5 | let service: CpdlcService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [CpdlcService] }).compile(); 9 | 10 | service = module.get(CpdlcService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/cpdlc/cpdlc.service.ts: -------------------------------------------------------------------------------- 1 | import { 2 | HttpException, 3 | HttpService, 4 | Injectable, Logger, 5 | } from '@nestjs/common'; 6 | import { catchError, map, tap } from 'rxjs/operators'; 7 | import { Cpdlc } from './cpdlc.class'; 8 | import { CacheService } from '../cache/cache.service'; 9 | import { CpdlcMessageDto } from './dto/cpdlc-message.dto'; 10 | 11 | @Injectable() 12 | export class CpdlcService { 13 | private readonly logger = new Logger(CpdlcService.name); 14 | 15 | constructor(private http: HttpService, 16 | private readonly cache: CacheService) { 17 | } 18 | 19 | async getData(dto: CpdlcMessageDto): Promise { 20 | const packet = `${dto.packet !== undefined ? `&packet=${encodeURIComponent(dto.packet)}`: ''}`; 21 | return this.http.get(`http://www.hoppie.nl/acars/system/connect.html?logon=${dto.logon}&from=${dto.from}&to=${dto.to}&type=${dto.type}${packet}`) 22 | .pipe( 23 | map((response) => { 24 | if (!response.data) { 25 | throw this.generateNotAvailableException('Empty response'); 26 | } 27 | 28 | return { response: response.data }; 29 | }), 30 | catchError( 31 | (err) => { 32 | throw this.generateNotAvailableException(err); 33 | }, 34 | ), 35 | ).toPromise(); 36 | } 37 | 38 | private generateNotAvailableException(err: any): HttpException { 39 | const exception = new HttpException('error {}', 404); 40 | this.logger.error(err); 41 | this.logger.error(exception); 42 | return exception; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/cpdlc/dto/cpdlc-message.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsOptional } from 'class-validator'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | 4 | export class CpdlcMessageDto { 5 | @IsNotEmpty() 6 | @ApiProperty({ description: 'The Hoppie logon code', example: 'xxxxxxxxxx' }) 7 | logon: string; 8 | 9 | @IsNotEmpty() 10 | @ApiProperty({ description: 'The from-callsign', example: 'DLH8HM' }) 11 | from: string; 12 | 13 | @IsNotEmpty() 14 | @ApiProperty({ description: 'The to-callsign', example: 'ALL-CALLSIGNS' }) 15 | to: string 16 | 17 | @IsNotEmpty() 18 | @ApiProperty({ description: 'The request type', example: 'poll' }) 19 | type: string; 20 | 21 | @IsOptional() 22 | @ApiProperty({ description: 'The message content', example: 'data2//1/Hello' }) 23 | packet?: string; 24 | } 25 | -------------------------------------------------------------------------------- /src/discord/discord.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpModule, Module } from '@nestjs/common'; 2 | import { DiscordService } from './discord.service'; 3 | 4 | @Module({ 5 | imports: [ 6 | HttpModule, 7 | ], 8 | providers: [DiscordService], 9 | controllers: [], 10 | exports: [DiscordService], 11 | }) 12 | export class DiscordModule {} 13 | -------------------------------------------------------------------------------- /src/discord/discord.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { map, tap } from 'rxjs/operators'; 3 | import { ConfigService } from '@nestjs/config'; 4 | import { TelexMessage } from '../telex/entities/telex-message.entity'; 5 | 6 | @Injectable() 7 | export class DiscordService { 8 | private readonly logger = new Logger(DiscordService.name); 9 | 10 | private readonly webhookUrl = this.configService.get('telex.discordWebhook'); 11 | 12 | constructor( 13 | private readonly http: HttpService, 14 | private readonly configService: ConfigService, 15 | ) { 16 | } 17 | 18 | public async publishTelexMessage(telexMessage: TelexMessage, blocked: boolean, ipBlocked: boolean): Promise { 19 | if (!this.webhookUrl) { 20 | this.logger.debug('Discord Webhook URL not configured -> skipping'); 21 | return; 22 | } 23 | 24 | let color = 6280776; // #5fd648 25 | color = telexMessage.isProfane ? 14671680 : color; // #dfdf40 26 | color = (blocked || ipBlocked) ? 14299698 : color; // #da3232 27 | 28 | const discordMessage = { 29 | embeds: [{ 30 | title: `${telexMessage.from.flight} -> ${telexMessage.to.flight}`, 31 | description: telexMessage.message, 32 | color, 33 | fields: [ 34 | { 35 | name: 'Sender ID', 36 | value: `\`${telexMessage.from.id}\``, 37 | inline: true, 38 | }, 39 | { 40 | name: 'Recipient ID', 41 | value: `\`${telexMessage.to.id}\``, 42 | inline: true, 43 | }, 44 | { 45 | name: 'Profanity', 46 | value: `\`${telexMessage.isProfane ? 'true' : 'false'}\``, 47 | inline: true, 48 | }, 49 | { 50 | name: 'Content Blocked', 51 | value: `\`${blocked ? 'true' : 'false'}\``, 52 | inline: true, 53 | }, 54 | { 55 | name: 'IP Blocked', 56 | value: `\`${ipBlocked ? 'true' : 'false'}\``, 57 | inline: true, 58 | }, 59 | ], 60 | }], 61 | }; 62 | 63 | await this.http.post(this.webhookUrl, discordMessage) 64 | .pipe( 65 | tap((response) => this.logger.debug(`Response status ${response.status} for Discord webhook request`)), 66 | map((response) => response.data), 67 | ) 68 | .toPromise(); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/git-versions/dto/artifact-info.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class ArtifactInfo { 4 | @ApiProperty({ description: 'URL of the artifact', example: 'https://.../zip' }) 5 | artifactUrl: string; 6 | } 7 | -------------------------------------------------------------------------------- /src/git-versions/dto/commit-info.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class CommitInfo { 4 | @ApiProperty({ description: 'The commit hash', example: '5160ea16c15868251f97ba4489304f328caafa8c' }) 5 | sha: string; 6 | 7 | @ApiProperty({ description: 'The shortened commit hash', example: '5160ea1' }) 8 | shortSha: string; 9 | 10 | @ApiProperty({ description: 'The time the commit was created' }) 11 | timestamp: Date; 12 | } 13 | -------------------------------------------------------------------------------- /src/git-versions/dto/pull-info.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { PullLabel } from './pull-label.dto'; 3 | 4 | export class PullInfo { 5 | @ApiProperty({ description: 'The number of the PR', example: '3176' }) 6 | number: number; 7 | 8 | @ApiProperty({ description: 'The title of the PR', example: 'feat: brake fan' }) 9 | title: string; 10 | 11 | @ApiProperty({ description: 'The username of the author', example: 'tyler58546' }) 12 | author: string; 13 | 14 | @ApiProperty({ description: 'The labels on the PR' }) 15 | labels: PullLabel[]; 16 | 17 | @ApiProperty({ description: 'Whether the PR is still a draft' }) 18 | isDraft: boolean; 19 | } 20 | -------------------------------------------------------------------------------- /src/git-versions/dto/pull-label.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class PullLabel { 4 | @ApiProperty({ description: 'The unique identifier of the label', example: 'MDU6TGFiZWwyMzQ1OTA5MjAz' }) 5 | id: string; 6 | 7 | @ApiProperty({ description: 'The name of the label', example: ['Ready to Test', 'QA Tier 2'] }) 8 | name: string; 9 | 10 | @ApiProperty({ description: 'The hex color of the label', example: 'd93f0b' }) 11 | color: string; 12 | } 13 | -------------------------------------------------------------------------------- /src/git-versions/dto/release-info.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class ReleaseInfo { 4 | @ApiProperty({ description: 'The name of the release', example: 'v0.5.1' }) 5 | name: string; 6 | 7 | @ApiProperty({ description: 'Whether the release is a pre-release' }) 8 | isPreRelease: boolean; 9 | 10 | @ApiProperty({ description: 'The publish timestamp of the release' }) 11 | publishedAt: Date; 12 | 13 | @ApiProperty({ description: 'The URL of the release page on GitHub' }) 14 | htmlUrl: string; 15 | 16 | @ApiProperty({ description: 'Markdown formatted body of the release' }) 17 | body: string; 18 | } 19 | -------------------------------------------------------------------------------- /src/git-versions/git-versions.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { GitVersionsController } from './git-versions.controller'; 3 | 4 | describe('GitVersionsController', () => { 5 | let controller: GitVersionsController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [GitVersionsController] }).compile(); 9 | 10 | controller = module.get(GitVersionsController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/git-versions/git-versions.controller.ts: -------------------------------------------------------------------------------- 1 | import { CacheInterceptor, CacheTTL, Controller, Get, Param, Query, UseInterceptors, ValidationPipe } from '@nestjs/common'; 2 | import { ApiOkResponse, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'; 3 | import { GitVersionsService } from './git-versions.service'; 4 | import { ReleaseInfo } from './dto/release-info.dto'; 5 | import { PullInfo } from './dto/pull-info.dto'; 6 | import { CommitInfo } from './dto/commit-info.dto'; 7 | import { ArtifactInfo } from './dto/artifact-info.dto'; 8 | import { PaginationDto } from '../common/Pagination'; 9 | 10 | @ApiTags('Git Versions') 11 | @Controller('api/v1/git-versions') 12 | @UseInterceptors(CacheInterceptor) 13 | export class GitVersionsController { 14 | constructor(private service: GitVersionsService) { 15 | } 16 | 17 | @Get(':user/:repo/branches/:branch') 18 | @CacheTTL(300) 19 | @ApiParam({ name: 'user', description: 'The owner of the repository', example: 'flybywiresim' }) 20 | @ApiParam({ name: 'repo', description: 'The repository', example: 'a32nx' }) 21 | @ApiParam({ name: 'branch', description: 'The target branch', example: 'master' }) 22 | @ApiOkResponse({ description: 'The newest commit on the branch', type: CommitInfo }) 23 | async getCommitOfBranch(@Param('user') user: string, @Param('repo') repo: string, @Param('branch') branch: string): Promise { 24 | try { 25 | return await this.service.getCommitOfBranch(user, repo, branch).toPromise(); 26 | } catch (e) { 27 | return { 28 | sha: '', 29 | shortSha: '', 30 | timestamp: new Date(), 31 | }; 32 | } 33 | } 34 | 35 | @Get(':user/:repo/releases') 36 | @CacheTTL(300) 37 | @ApiParam({ name: 'user', description: 'The owner of the repository', example: 'flybywiresim' }) 38 | @ApiParam({ name: 'repo', description: 'The repository', example: 'a32nx' }) 39 | @ApiQuery({ 40 | name: 'take', 41 | type: Number, 42 | required: false, 43 | description: 'The number of releases to take', 44 | schema: { maximum: 25, minimum: 0, default: 25 }, 45 | }) 46 | @ApiQuery({ 47 | name: 'skip', 48 | type: Number, 49 | required: false, 50 | description: 'The number of releases to skip', 51 | schema: { minimum: 0, default: 0 }, 52 | }) 53 | @ApiQuery({ 54 | name: 'includePreReleases', 55 | description: 'Whether to include pre-releases in the list', 56 | required: false, 57 | enum: ['true', 'false'], 58 | schema: { default: false }, 59 | }) 60 | @ApiOkResponse({ description: 'The paginated releases', type: [ReleaseInfo] }) 61 | async getReleases( 62 | @Param('user') user: string, 63 | @Param('repo') repo: string, 64 | @Query('includePreReleases') includePre: string, 65 | @Query(new ValidationPipe({ transform: true })) pagination: PaginationDto, 66 | ): Promise { 67 | try { 68 | return await this.service.getReleases(user, repo, includePre === undefined ? false : includePre === 'true', pagination).toPromise(); 69 | } catch (e) { 70 | return []; 71 | } 72 | } 73 | 74 | @Get(':user/:repo/pulls') 75 | @CacheTTL(60) 76 | @ApiParam({ name: 'user', description: 'The owner of the repository', example: 'flybywiresim' }) 77 | @ApiParam({ name: 'repo', description: 'The repository', example: 'a32nx' }) 78 | @ApiOkResponse({ description: 'The newest PRs of the repo', type: [PullInfo] }) 79 | async getPulls(@Param('user') user: string, @Param('repo') repo: string): Promise { 80 | try { 81 | return await this.service.getPulls(user, repo).toPromise(); 82 | } catch (e) { 83 | return []; 84 | } 85 | } 86 | 87 | @Get(':user/:repo/pulls/:pull/artifact') 88 | @CacheTTL(60) 89 | @ApiParam({ name: 'user', description: 'The owner of the repository', example: 'flybywiresim' }) 90 | @ApiParam({ name: 'repo', description: 'The repository', example: 'a32nx' }) 91 | @ApiParam({ name: 'pull', description: 'The number of the PR', example: '3295' }) 92 | @ApiOkResponse({ description: 'The artifact URL for this PR', type: ArtifactInfo }) 93 | async getArtifact(@Param('user') user: string, @Param('repo') repo: string, @Param('pull') pull: string): Promise { 94 | try { 95 | return await this.service.getArtifactForPull(user, repo, pull); 96 | } catch (e) { 97 | return { artifactUrl: '' }; 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/git-versions/git-versions.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpModule, Module } from '@nestjs/common'; 2 | import { GitVersionsService } from './git-versions.service'; 3 | import { GitVersionsController } from './git-versions.controller'; 4 | 5 | @Module({ 6 | imports: [HttpModule], 7 | providers: [GitVersionsService], 8 | controllers: [GitVersionsController], 9 | }) 10 | export class GitVersionsModule {} 11 | -------------------------------------------------------------------------------- /src/git-versions/git-versions.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { GitVersionsService } from './git-versions.service'; 3 | 4 | describe('GitVersionsService', () => { 5 | let service: GitVersionsService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [GitVersionsService] }).compile(); 9 | 10 | service = module.get(GitVersionsService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/git-versions/git-versions.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { Observable } from 'rxjs'; 3 | import { catchError, map, tap } from 'rxjs/operators'; 4 | import { ConfigService } from '@nestjs/config'; 5 | import { CommitInfo } from './dto/commit-info.dto'; 6 | import { ReleaseInfo } from './dto/release-info.dto'; 7 | import { PullInfo } from './dto/pull-info.dto'; 8 | import { ArtifactInfo } from './dto/artifact-info.dto'; 9 | import { PaginationDto } from '../common/Pagination'; 10 | 11 | @Injectable() 12 | export class GitVersionsService { 13 | private readonly logger = new Logger(GitVersionsService.name); 14 | 15 | private readonly headers: any; 16 | 17 | constructor(private readonly http: HttpService, 18 | private readonly configService: ConfigService) { 19 | const token = this.configService.get('github.token'); 20 | 21 | if (token) { 22 | this.headers = { Authorization: `token ${token}` }; 23 | } 24 | } 25 | 26 | getCommitOfBranch(user: string, repo: string, branch: string): Observable { 27 | this.logger.debug(`Trying to fetch commit info for ${user}/${repo}/refs/${branch}`); 28 | 29 | return this.http.get(`https://api.github.com/repos/${user}/${repo}/commits/${branch}`, { headers: this.headers }) 30 | .pipe( 31 | tap((response) => this.logger.debug(`Response status ${response.status} for GitHub commit request`)), 32 | map((response) => ({ 33 | sha: response.data.sha, 34 | shortSha: response.data.sha.slice(0, 7), 35 | timestamp: response.data.commit.committer.date, 36 | })), 37 | catchError( 38 | (err) => { 39 | this.logger.error(err); 40 | throw new HttpException('Could not fetch GitHub commit', err.response.status || err.status || 500); 41 | }, 42 | ), 43 | ); 44 | } 45 | 46 | getReleases(user: string, repo: string, includePreReleases: boolean, pagination: PaginationDto): Observable { 47 | this.logger.debug(`Trying to fetch releases for ${user}/${repo}`); 48 | 49 | // Fetch GH releases 50 | // We need to fetch all and can't use GH pagination because we filter for pre-releases, which GH API doesn't support 51 | return this.http.get(`https://api.github.com/repos/${user}/${repo}/releases`, { headers: this.headers }) 52 | .pipe( 53 | tap((response) => this.logger.debug(`Response status ${response.status} for GitHub commit request`)), 54 | map((response) => { 55 | const releases: ReleaseInfo[] = []; 56 | 57 | response.data.filter((rel) => includePreReleases || !rel.prerelease).forEach((rel) => { 58 | releases.push({ 59 | name: rel.name, 60 | isPreRelease: rel.prerelease, 61 | htmlUrl: rel.html_url, 62 | publishedAt: rel.published_at, 63 | body: rel.body, 64 | }); 65 | }); 66 | 67 | return releases.slice(pagination.skip, pagination.skip + pagination.take); 68 | }), 69 | catchError( 70 | (err) => { 71 | this.logger.error(err); 72 | throw new HttpException('Could not fetch GitHub releases', err.response.status || err.status || 500); 73 | }, 74 | ), 75 | ); 76 | } 77 | 78 | getPulls(user: string, repo: string): Observable { 79 | this.logger.debug(`Trying to fetch pulls for ${user}/${repo}`); 80 | 81 | return this.http.post('https://api.github.com/graphql', { 82 | query: `{repository(owner:"${user}",name:"${repo}"){pullRequests(first:100,states:OPEN) 83 | {nodes{number title state isDraft author{login}labels(first:10){nodes{name color id}}}}}}`, 84 | }, { headers: this.headers }) 85 | .pipe( 86 | tap((response) => this.logger.debug(`Response status ${response.status} for GitHub pull requests`)), 87 | map((response) => { 88 | const pulls: PullInfo[] = []; 89 | 90 | response.data.data.repository.pullRequests.nodes.forEach((pull) => { 91 | pulls.push({ 92 | number: pull.number, 93 | title: pull.title, 94 | author: pull.author.login, 95 | labels: pull.labels.nodes, 96 | isDraft: pull.isDraft, 97 | }); 98 | }); 99 | 100 | return pulls; 101 | }), 102 | catchError( 103 | (err) => { 104 | this.logger.error(err); 105 | throw new HttpException('Could not fetch GitHub pull requests', err.response?.status || err.status || 500); 106 | }, 107 | ), 108 | ); 109 | } 110 | 111 | async getArtifactForPull(user: string, repo: string, pull: string): Promise { 112 | // Fuck you GH API for making me do this 113 | const checkIds = await this.http.get(`https://github.com/${user}/${repo}/pull/${pull}/checks`, { headers: this.headers }) 114 | .pipe( 115 | tap((response) => this.logger.debug(`Response status ${response.status} for GitHub pull request checks`)), 116 | map((response) => { 117 | const matches = response.data.match(new RegExp(` { 128 | this.logger.error(err); 129 | throw new HttpException('Could not fetch GitHub checks for PR', err.response?.status || err.status || 500); 130 | }, 131 | ), 132 | ).toPromise(); 133 | 134 | const artifacts = await Promise.all(checkIds.map(async (checkId) => this.http.get( 135 | `https://api.github.com/repos/${user}/${repo}/actions/runs/${checkId}/artifacts`, { headers: this.headers }, 136 | ) 137 | .pipe( 138 | tap((response) => this.logger.debug(`Response status ${response.status} for GitHub artifact request`)), 139 | map((response) => { 140 | if (response.data.total_count !== 1) { 141 | return undefined; 142 | } 143 | 144 | return response.data.artifacts[0].archive_download_url; 145 | }), 146 | catchError( 147 | (err) => { 148 | this.logger.error(err); 149 | throw new HttpException('Could not fetch GitHub artifact for check', err.response?.status || err.status || 500); 150 | }, 151 | ), 152 | ).toPromise())); 153 | 154 | if (!artifacts.some((x) => x !== undefined)) { 155 | throw new HttpException('Could not find artifact for PR', 404); 156 | } 157 | 158 | return { artifactUrl: artifacts.find((x) => x !== undefined) }; 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /src/gnss/dto/satellite-info.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class SatelliteInfo { 4 | @ApiProperty({ description: 'The name of the satellite', example: 'GPS BIIR-2 (PRN 13)' }) 5 | name: string; 6 | 7 | @ApiProperty() 8 | id: string; 9 | 10 | @ApiProperty() 11 | epoch: Date; 12 | 13 | @ApiProperty() 14 | meanMotion: number; 15 | 16 | @ApiProperty() 17 | eccentricity: number; 18 | 19 | @ApiProperty() 20 | inclination: number; 21 | 22 | @ApiProperty() 23 | raOfAscNode: number; 24 | 25 | @ApiProperty() 26 | argOfPericenter: number; 27 | 28 | @ApiProperty() 29 | meanAnomaly: number; 30 | 31 | @ApiProperty() 32 | ephemerisType: number; 33 | 34 | @ApiProperty() 35 | classificationType: string; 36 | 37 | @ApiProperty() 38 | noradCatId: number; 39 | 40 | @ApiProperty() 41 | elementSetNo: number; 42 | 43 | @ApiProperty() 44 | revAtEpoch: number; 45 | 46 | @ApiProperty() 47 | bstar: number; 48 | 49 | @ApiProperty() 50 | meanMotionDot: number; 51 | 52 | @ApiProperty() 53 | meanMotionDdot: number; 54 | } 55 | -------------------------------------------------------------------------------- /src/gnss/gnss.controller.ts: -------------------------------------------------------------------------------- 1 | import { ApiOkResponse, ApiTags } from '@nestjs/swagger'; 2 | import { CacheInterceptor, CacheTTL, Controller, Get, Logger, UseInterceptors } from '@nestjs/common'; 3 | import { Observable } from 'rxjs'; 4 | import { Cron } from '@nestjs/schedule'; 5 | import { GnssService } from './gnss.service'; 6 | import { SatelliteInfo } from './dto/satellite-info.dto'; 7 | import { CacheService } from '../cache/cache.service'; 8 | 9 | @ApiTags('GNSS') 10 | @Controller('api/v1/gnss') 11 | @UseInterceptors(CacheInterceptor) 12 | export class GnssController { 13 | private readonly logger = new Logger(GnssController.name); 14 | 15 | constructor( 16 | private service: GnssService, 17 | private cache: CacheService, 18 | ) {} 19 | 20 | @Get() 21 | @CacheTTL(3600) // 1h 22 | @ApiOkResponse({ description: 'Satellite data for the GNSS constellation', type: [SatelliteInfo] }) 23 | getGnssInfo(): Observable { 24 | return this.service.getGnssInfo(); 25 | } 26 | 27 | @Cron('0 1 * * *') 28 | async clearCache() { 29 | try { 30 | this.logger.log('Clearing GNSS cache'); 31 | await this.cache.del('/api/v1/gnss'); 32 | } catch (e) { 33 | this.logger.error(e); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/gnss/gnss.module.ts: -------------------------------------------------------------------------------- 1 | import { HttpModule, Module } from '@nestjs/common'; 2 | import { GnssService } from './gnss.service'; 3 | import { GnssController } from './gnss.controller'; 4 | 5 | @Module({ 6 | imports: [HttpModule], 7 | providers: [GnssService], 8 | controllers: [GnssController], 9 | }) 10 | export class GnssModule {} 11 | -------------------------------------------------------------------------------- /src/gnss/gnss.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { map, tap } from 'rxjs/operators'; 3 | import { Observable } from 'rxjs'; 4 | import { SatelliteInfo } from './dto/satellite-info.dto'; 5 | 6 | @Injectable() 7 | export class GnssService { 8 | private readonly logger = new Logger(GnssService.name); 9 | 10 | constructor(private readonly http: HttpService) { 11 | } 12 | 13 | public getGnssInfo(): Observable { 14 | return this.http.get('https://celestrak.com/NORAD/elements/gp.php?GROUP=gnss&FORMAT=json') 15 | .pipe( 16 | tap((response) => this.logger.debug(`Response status ${response.status} for Celestrak request`)), 17 | map((response) => response.data), 18 | map((data) => data.map((info) => ({ 19 | name: info.OBJECT_NAME, 20 | id: info.OBJECT_ID, 21 | epoch: new Date(info.EPOCH), 22 | meanMotion: info.MEAN_MOTION, 23 | eccentricity: info.ECCENTRICITY, 24 | inclination: info.INCLINATION, 25 | raOfAscNode: info.RA_OF_ASC_NODE, 26 | argOfPericenter: info.ARG_OF_PERICENTER, 27 | meanAnomaly: info.MEAN_ANOMALY, 28 | ephemerisType: info.EPHEMERIS_TYPE, 29 | classificationType: info.CLASSIFICATION_TYPE, 30 | noradCatId: info.NORAD_CAT_ID, 31 | elementSetNo: info.ELEMENT_SET_NO, 32 | revAtEpoch: info.REV_AT_EPOCH, 33 | bstar: info.BSTAR, 34 | meanMotionDot: info.MEAN_MOTION_DOT, 35 | meanMotionDdot: info.MEAN_MOTION_DDOT, 36 | }))), 37 | ); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/health/health.controller.ts: -------------------------------------------------------------------------------- 1 | import { Controller, Get } from '@nestjs/common'; 2 | import { ApiTags } from '@nestjs/swagger'; 3 | import { DNSHealthIndicator, HealthCheck, HealthCheckService, TypeOrmHealthIndicator } from '@nestjs/terminus'; 4 | 5 | @ApiTags('HEALTH') 6 | @Controller('health') 7 | export class HealthController { 8 | constructor( 9 | private health: HealthCheckService, 10 | private dns: DNSHealthIndicator, 11 | private db: TypeOrmHealthIndicator, 12 | ) { } 13 | 14 | @Get() 15 | @HealthCheck() 16 | check() { 17 | return this.health.check([ 18 | () => this.db.pingCheck('database', { timeout: 8000 }), 19 | ]); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/health/health.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TerminusModule } from '@nestjs/terminus'; 3 | 4 | import { HealthController } from './health.controller'; 5 | 6 | @Module({ 7 | imports: [TerminusModule], 8 | controllers: [HealthController], 9 | }) 10 | export class HealthModule { } 11 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; 3 | import * as requestIp from 'request-ip'; 4 | import * as helmet from 'helmet'; 5 | import * as rateLimit from 'express-rate-limit'; 6 | import { NestExpressApplication } from '@nestjs/platform-express'; 7 | import { ValidationPipe } from '@nestjs/common'; 8 | import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston'; 9 | import { start } from 'elastic-apm-node'; 10 | import { AppModule } from './app.module'; 11 | 12 | start(); 13 | 14 | async function bootstrap() { 15 | const app = await NestFactory.create(AppModule, { logger: true }); 16 | 17 | app.useLogger(app.get(WINSTON_MODULE_NEST_PROVIDER)); 18 | 19 | // correct source IP 20 | app.use(requestIp.mw()); 21 | app.set('trust proxy', 1); 22 | 23 | // Protect against a multitude of attack scenarios 24 | app.use(helmet()); 25 | 26 | // CORS 27 | app.enableCors(); 28 | 29 | // Request param/body/query validation 30 | app.useGlobalPipes(new ValidationPipe({ whitelist: true })); 31 | 32 | // Rate limiter 33 | app.use( 34 | rateLimit({ 35 | windowMs: 15 * 60 * 1000, // 15 minutes 36 | max: 500, // limit each IP to 500 requests per windowMs 37 | }), 38 | ); 39 | 40 | // Swagger 41 | const options = new DocumentBuilder() 42 | .setTitle('FlyByWire Simulations API') 43 | .setDescription('The FlyByWire Simulations API description') 44 | .setVersion('1.0') 45 | .addSecurity('jwt', { 46 | type: 'http', 47 | scheme: 'bearer', 48 | bearerFormat: 'JWT', 49 | }) 50 | .build(); 51 | const document = SwaggerModule.createDocument(app, options); 52 | SwaggerModule.setup('api', app, document); 53 | 54 | await app.listen(3000); 55 | } 56 | 57 | bootstrap(); 58 | -------------------------------------------------------------------------------- /src/metar/metar.class.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class Metar { 4 | @ApiProperty({ description: 'The airport ICAO', example: 'KLAX' }) 5 | icao: string; 6 | 7 | @ApiProperty({ 8 | description: 'The TAF notice', 9 | example: 'KLAX 242253Z 26012KT 10SM FEW025 SCT043 BKN240 20/12 A2993 RMK AO2 SLP134 T02000122', 10 | }) 11 | metar: string; 12 | 13 | @ApiProperty({ description: 'The source of the METAR notice', enum: ['vatsim', 'ms', 'ivao', 'pilotedge'] }) 14 | source: string; 15 | } 16 | -------------------------------------------------------------------------------- /src/metar/metar.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { MetarController } from './metar.controller'; 3 | 4 | describe('MetarController', () => { 5 | let controller: MetarController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [MetarController] }).compile(); 9 | 10 | controller = module.get(MetarController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/metar/metar.controller.ts: -------------------------------------------------------------------------------- 1 | import { CacheInterceptor, CacheTTL, Controller, Get, Param, Query, UseInterceptors } from '@nestjs/common'; 2 | import { ApiNotFoundResponse, ApiOkResponse, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'; 3 | import { MetarService } from './metar.service'; 4 | import { Metar } from './metar.class'; 5 | 6 | @ApiTags('METAR') 7 | @Controller('metar') 8 | @UseInterceptors(CacheInterceptor) 9 | export class MetarController { 10 | constructor(private metar: MetarService) { 11 | } 12 | 13 | @Get(':icao') 14 | @CacheTTL(240) 15 | @ApiParam({ name: 'icao', description: 'The ICAO of the airport to search for', example: 'KLAX' }) 16 | @ApiQuery({ 17 | name: 'source', 18 | description: 'The source for the METAR', 19 | example: 'vatsim', 20 | required: false, 21 | enum: ['vatsim', 'ms', 'ivao', 'pilotedge', 'aviationweather'], 22 | }) 23 | @ApiOkResponse({ description: 'METAR notice was found', type: Metar }) 24 | @ApiNotFoundResponse({ description: 'METAR not available for ICAO' }) 25 | getForICAO(@Param('icao') icao: string, @Query('source') source?: string): Promise { 26 | return this.metar.getForICAO(icao, source); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/metar/metar.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { MetarService } from './metar.service'; 3 | 4 | describe('MetarService', () => { 5 | let service: MetarService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [MetarService] }).compile(); 9 | 10 | service = module.get(MetarService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/metar/metar.service.ts: -------------------------------------------------------------------------------- 1 | import { 2 | HttpException, 3 | HttpService, 4 | Injectable, Logger, 5 | } from '@nestjs/common'; 6 | import { Observable } from 'rxjs'; 7 | import { catchError, map, tap } from 'rxjs/operators'; 8 | import { Metar } from './metar.class'; 9 | import { CacheService } from '../cache/cache.service'; 10 | 11 | @Injectable() 12 | export class MetarService { 13 | private readonly logger = new Logger(MetarService.name); 14 | 15 | constructor(private http: HttpService, 16 | private readonly cache: CacheService) { 17 | } 18 | 19 | getForICAO(icao: string, source?: string): Promise { 20 | const icaoCode = icao.toUpperCase(); 21 | this.logger.debug(`Searching for ICAO ${icaoCode} from source ${source}`); 22 | 23 | switch (source?.toLowerCase()) { 24 | case 'vatsim': 25 | default: 26 | return this.handleVatsim(icaoCode).toPromise(); 27 | case 'ms': 28 | return this.handleMs(icaoCode); 29 | case 'pilotedge': 30 | return this.handlePilotEdge(icaoCode).toPromise(); 31 | case 'aviationweather': 32 | return this.handleAviationWeather(icaoCode).toPromise(); 33 | } 34 | } 35 | 36 | // Vatsim 37 | private handleVatsim(icao: string): Observable { 38 | return this.http.get(`http://metar.vatsim.net/metar.php?id=${icao}`) 39 | .pipe( 40 | tap((response) => this.logger.debug(`Response status ${response.status} for Vatsim METAR request`)), 41 | map((response) => { 42 | if (!response.data) { 43 | throw this.generateNotAvailableException('Empty response', icao); 44 | } 45 | 46 | return { icao, metar: response.data, source: 'Vatsim' }; 47 | }), 48 | catchError( 49 | (err) => { 50 | throw this.generateNotAvailableException(err, icao); 51 | }, 52 | ), 53 | ); 54 | } 55 | 56 | // MS 57 | async fetchMsBlob(): Promise { 58 | const cacheHit = await this.cache.get('/metar/blob/ms'); 59 | 60 | if (cacheHit) { 61 | this.logger.debug('Returning from cache'); 62 | return cacheHit; 63 | } 64 | const data = await this.http.get('https://fsxweatherstorage.blob.core.windows.net/fsxweather/metars.bin') 65 | .pipe( 66 | tap((response) => this.logger.debug(`Response status ${response.status} for MS METAR request`)), 67 | map((response) => response.data.split(/\r?\n/)), 68 | ).toPromise(); 69 | 70 | this.cache.set('/metar/blob/ms', data, 240).then(); 71 | return data; 72 | } 73 | 74 | private handleMs(icao: string): Promise { 75 | return this.fetchMsBlob() 76 | .then((response) => ({ icao, metar: response.find((x) => x.startsWith(icao)), source: 'MS' })) 77 | .catch((e) => { 78 | throw this.generateNotAvailableException(e, icao); 79 | }); 80 | } 81 | 82 | // IVAO 83 | private async fetchIvaoBlob(): Promise { 84 | const cacheHit = await this.cache.get('/metar/blob/ivao'); 85 | 86 | if (cacheHit) { 87 | this.logger.debug('Returning from cache'); 88 | return cacheHit; 89 | } 90 | const data = await this.http.get('http://wx.ivao.aero/metar.php') 91 | .pipe( 92 | tap((response) => this.logger.debug(`Response status ${response.status} for IVAO METAR request`)), 93 | map((response) => response.data.split(/\r?\n/)), 94 | ).toPromise(); 95 | 96 | this.cache.set('/metar/blob/ivao', data, 240).then(); 97 | return data; 98 | } 99 | 100 | private handleIvao(icao: string): Promise { 101 | return this.fetchIvaoBlob() 102 | .then((response) => ({ icao, metar: response.find((x) => x.startsWith(icao)), source: 'IVAO' })) 103 | .catch((e) => { 104 | throw this.generateNotAvailableException(e, icao); 105 | }); 106 | } 107 | 108 | // PilotEdge 109 | private handlePilotEdge(icao: string): Observable { 110 | return this.http.get(`https://www.pilotedge.net/atis/${icao}.json`) 111 | .pipe( 112 | tap((response) => this.logger.debug(`Response status ${response.status} for PilotEdge METAR request`)), 113 | map((response) => ({ icao, metar: response.data.metar, source: 'PilotEdge' })), 114 | catchError( 115 | (err) => { 116 | throw this.generateNotAvailableException(err, icao); 117 | }, 118 | ), 119 | ); 120 | } 121 | 122 | // AviationWeather 123 | private handleAviationWeather(icao: string): Observable { 124 | return this.http.get(`https://aviationweather.gov/api/data/metar?hours=0&ids=${icao}`, { responseType: 'text' }) 125 | .pipe( 126 | tap((response) => this.logger.debug(`Response status ${response.status} for AviationWeather METAR request`)), 127 | map((response) => { 128 | const metars = response.data.replace(/[\s$]+$/g, '').split('\n'); 129 | 130 | return ({ 131 | source: 'AviationWeather', 132 | icao, 133 | metar: metars.find((x) => x.startsWith(icao)).toUpperCase() 134 | }); 135 | }), 136 | catchError( 137 | (err) => { 138 | throw this.generateNotAvailableException(err, icao); 139 | }, 140 | ), 141 | ); 142 | } 143 | 144 | private generateNotAvailableException(err: any, icao: string): HttpException { 145 | const exception = new HttpException(`METAR not available for ICAO: ${icao}`, 404); 146 | this.logger.error(err); 147 | this.logger.error(exception); 148 | return exception; 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /src/taf/taf.class.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class Taf { 4 | @ApiProperty({ description: 'The airport ICAO', example: 'KLAX' }) 5 | icao: string; 6 | 7 | @ApiProperty({ 8 | description: 'The TAF notice', 9 | example: 'KLAX 242119Z 2421/2524 28011KT P6SM SCT029 OVC040 FM250500 26007KT P6SM OVC030 ' 10 | + 'FM250900 25007KT P6SM OVC035 FM251800 25010KT P6SM OVC040 FM252100 25013KT P6SM BKN045', 11 | }) 12 | taf: string; 13 | 14 | @ApiProperty({ description: 'The source of the TAF notice', enum: ['aviationweather', 'faa'] }) 15 | source: string; 16 | } 17 | -------------------------------------------------------------------------------- /src/taf/taf.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TafController } from './taf.controller'; 3 | 4 | describe('TafController', () => { 5 | let controller: TafController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [TafController] }).compile(); 9 | 10 | controller = module.get(TafController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/taf/taf.controller.ts: -------------------------------------------------------------------------------- 1 | import { CacheInterceptor, CacheTTL, Controller, Get, Param, Query, UseInterceptors } from '@nestjs/common'; 2 | import { ApiNotFoundResponse, ApiOkResponse, ApiParam, ApiQuery, ApiTags } from '@nestjs/swagger'; 3 | import { TafService } from './taf.service'; 4 | import { Taf } from './taf.class'; 5 | 6 | @ApiTags('TAF') 7 | @Controller('taf') 8 | @UseInterceptors(CacheInterceptor) 9 | export class TafController { 10 | constructor(private taf: TafService) { 11 | } 12 | 13 | @Get(':icao') 14 | @CacheTTL(120) 15 | @ApiParam({ name: 'icao', description: 'The ICAO of the airport to search for', example: 'KLAX' }) 16 | @ApiQuery({ name: 'source', description: 'The source for the TAF', example: 'faa', required: false, enum: ['aviationweather', 'faa'] }) 17 | @ApiOkResponse({ description: 'TAF notice was found', type: Taf }) 18 | @ApiNotFoundResponse({ description: 'TAF not available for ICAO' }) 19 | getForICAO(@Param('icao') icao: string, @Query('source') source?: string): Promise { 20 | return this.taf.getForICAO(icao, source); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/taf/taf.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TafService } from './taf.service'; 3 | 4 | describe('TafService', () => { 5 | let service: TafService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [TafService] }).compile(); 9 | 10 | service = module.get(TafService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/taf/taf.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { Observable } from 'rxjs'; 3 | import { catchError, map, tap } from 'rxjs/operators'; 4 | import { Taf } from './taf.class'; 5 | import { CacheService } from '../cache/cache.service'; 6 | 7 | // TODO: investigate 8 | // For some reason iconv is not working with import 9 | // eslint-disable-next-line @typescript-eslint/no-var-requires 10 | const iconv = require('iconv-lite'); 11 | 12 | @Injectable() 13 | export class TafService { 14 | private readonly logger = new Logger(TafService.name); 15 | 16 | constructor(private http: HttpService, 17 | private readonly cache: CacheService) { 18 | } 19 | 20 | getForICAO(icao: string, source?: string): Promise { 21 | const icaoCode = icao.toUpperCase(); 22 | this.logger.debug(`Searching for ICAO ${icaoCode} from source ${source}`); 23 | 24 | switch (source?.toLowerCase()) { 25 | case 'aviationweather': 26 | default: 27 | return this.handleAviationWeather(icaoCode).toPromise(); 28 | case 'faa': 29 | return this.handleFaa(icaoCode); 30 | } 31 | } 32 | 33 | // AviationWeather 34 | private handleAviationWeather(icao: string): Observable { 35 | return this.http.get( 36 | `https://aviationweather.gov/api/data/taf?ids=${icao}`, 37 | { responseType: 'text' }, 38 | ) 39 | .pipe( 40 | tap((response) => this.logger.debug(`Response status ${response.status} for AviationWeather TAF request`)), 41 | map((response) => { 42 | const tafs = response.data.replace(/\s\s+/g, ' ').trimEnd().split('\n'); 43 | 44 | return { 45 | source: 'AviationWeather', 46 | icao, 47 | taf: tafs.find((x) => x.startsWith(icao)).toUpperCase(), 48 | }; 49 | }), 50 | catchError( 51 | (err) => { 52 | throw this.generateNotAvailableException(err, icao); 53 | }, 54 | ), 55 | ); 56 | } 57 | 58 | // FAA 59 | private async fetchFaaBlob(): Promise { 60 | const cacheHit = await this.cache.get('/taf/blob/faa'); 61 | 62 | if (cacheHit) { 63 | this.logger.debug('Returning from cache'); 64 | return cacheHit; 65 | } 66 | const data = await this.http.get('http://wx.ivao.aero/taf.php') 67 | .pipe( 68 | tap((response) => this.logger.debug(`Response status ${response.status} for FAA TAF request`)), 69 | map((response) => iconv 70 | .decode(response.data, 'ISO-8859-1') 71 | .split(/\r?\n/)), 72 | ).toPromise(); 73 | 74 | this.cache.set('/taf/blob/faa', data, 240).then(); 75 | return data; 76 | } 77 | 78 | private handleFaa(icao: string): Promise { 79 | return this.fetchFaaBlob() 80 | .then((response) => ({ 81 | source: 'FAA', 82 | icao, 83 | taf: response.find((x) => x.startsWith(icao)).toUpperCase(), 84 | })) 85 | .catch((e) => { 86 | throw this.generateNotAvailableException(e, icao); 87 | }); 88 | } 89 | 90 | private generateNotAvailableException(err: any, icao: string): HttpException { 91 | const exception = new HttpException(`TAF not available for ICAO: ${icao}`, 404); 92 | this.logger.error(err); 93 | this.logger.error(exception); 94 | return exception; 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/telex/dto/create-telex-connection.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty } from 'class-validator'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | import { UpdateTelexConnectionDto } from './update-telex-connection.dto'; 4 | 5 | export class CreateTelexConnectionDto extends UpdateTelexConnectionDto { 6 | @IsNotEmpty() 7 | @ApiProperty({ description: 'The flight number', example: 'OS355' }) 8 | flight: string; 9 | } 10 | -------------------------------------------------------------------------------- /src/telex/dto/paginated-telex-connection.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty } from 'class-validator'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | import { TelexConnection } from '../entities/telex-connection.entity'; 4 | 5 | export class PaginatedTelexConnectionDto { 6 | @IsNotEmpty() 7 | @ApiProperty({ description: 'List of TELEX connections', type: [TelexConnection] }) 8 | results: TelexConnection[]; 9 | 10 | @IsNotEmpty() 11 | @ApiProperty({ description: 'Amount of connections returned', example: '25' }) 12 | count: number; 13 | 14 | @IsNotEmpty() 15 | @ApiProperty({ description: 'The number of total active connections in the boundary', example: '1237' }) 16 | total: number; 17 | } 18 | -------------------------------------------------------------------------------- /src/telex/dto/telex-message.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty } from 'class-validator'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | 4 | export class TelexMessageDto { 5 | @IsNotEmpty() 6 | @ApiProperty({ description: 'The number of the recipient flight', example: 'OS355' }) 7 | to: string; 8 | 9 | @IsNotEmpty() 10 | @ApiProperty({ description: 'The message to send', example: 'Hello over there!' }) 11 | message: string; 12 | } 13 | -------------------------------------------------------------------------------- /src/telex/dto/telex-search-result.dto.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | import { TelexConnection } from '../entities/telex-connection.entity'; 3 | 4 | export class TelexSearchResult { 5 | @ApiProperty({ description: 'A possible full text match' }) 6 | fullMatch?: TelexConnection; 7 | 8 | @ApiProperty({ description: 'All possible matches', type: [TelexConnection] }) 9 | matches: TelexConnection[]; 10 | } 11 | -------------------------------------------------------------------------------- /src/telex/dto/update-telex-connection.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsNotEmpty, IsOptional } from 'class-validator'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | import { Point } from '../entities/point.entity'; 4 | 5 | export class UpdateTelexConnectionDto { 6 | @IsNotEmpty() 7 | @ApiProperty({ description: 'The current location of the aircraft' }) 8 | location: Point; 9 | 10 | @IsNotEmpty() 11 | @ApiProperty({ description: 'The altitude above sea level of the aircraft in feet', example: 3500 }) 12 | trueAltitude: number; 13 | 14 | @IsNotEmpty() 15 | @ApiProperty({ description: 'The heading the aircraft in degrees', example: 250.46, minimum: 0, maximum: 360 }) 16 | heading: number; 17 | 18 | @IsOptional() 19 | @ApiProperty({ description: 'Whether the user wants to receive freetext messages', example: true }) 20 | freetextEnabled: boolean; 21 | 22 | @IsOptional() 23 | @ApiProperty({ description: 'The aircraft type the connection associated with', example: 'A32NX' }) 24 | aircraftType = 'unknown'; 25 | 26 | @IsOptional() 27 | @ApiProperty({ description: 'The destination of the flight', example: 'KSFO', required: false }) 28 | destination?: string; 29 | 30 | @IsOptional() 31 | @ApiProperty({ description: 'The origin of the flight', example: 'KLAX', required: false }) 32 | origin?: string; 33 | } 34 | -------------------------------------------------------------------------------- /src/telex/entities/blocked-ip.entity.ts: -------------------------------------------------------------------------------- 1 | import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm'; 2 | 3 | @Entity() 4 | export class BlockedIp { 5 | @PrimaryGeneratedColumn('uuid') 6 | id?: string; 7 | 8 | @Column() 9 | @Index() 10 | ip: string; 11 | 12 | @Column({ default: true }) 13 | @Index() 14 | isActive?: boolean; 15 | 16 | @CreateDateColumn() 17 | createdAt?: Date; 18 | 19 | @UpdateDateColumn() 20 | lastModifiedAt?: Date; 21 | 22 | @Column() 23 | reason: string; 24 | } 25 | -------------------------------------------------------------------------------- /src/telex/entities/point.entity.ts: -------------------------------------------------------------------------------- 1 | import { ApiProperty } from '@nestjs/swagger'; 2 | 3 | export class Point { 4 | @ApiProperty({ description: 'The X coordinate' }) 5 | x: number; 6 | 7 | @ApiProperty({ description: 'The Y coordinate' }) 8 | y: number; 9 | } 10 | -------------------------------------------------------------------------------- /src/telex/entities/telex-connection.entity.ts: -------------------------------------------------------------------------------- 1 | import { Column, CreateDateColumn, Entity, Index, PrimaryGeneratedColumn, UpdateDateColumn } from 'typeorm'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | import { Point } from './point.entity'; 4 | 5 | @Entity() 6 | export class TelexConnection { 7 | @PrimaryGeneratedColumn('uuid') 8 | @ApiProperty({ 9 | description: 'The unique identifier of the connection', 10 | example: '6571f19e-21f7-4080-b239-c9d649347101', 11 | }) 12 | id?: string; 13 | 14 | @Column({ default: true }) 15 | @Index() 16 | @ApiProperty({ description: 'Whether the connection is an active on or not' }) 17 | isActive?: boolean; 18 | 19 | @CreateDateColumn() 20 | @Index() 21 | @ApiProperty({ description: 'The time of first contact' }) 22 | firstContact?: Date; 23 | 24 | @UpdateDateColumn() 25 | @Index() 26 | @ApiProperty({ description: 'The time of last contact' }) 27 | lastContact?: Date; 28 | 29 | @Column({ update: false }) 30 | @Index() 31 | @ApiProperty({ description: 'The flight number', example: 'OS355' }) 32 | flight: string; 33 | 34 | @Column({ 35 | type: 'point', 36 | nullable: false, 37 | transformer: { 38 | from: (v) => ({ 39 | x: Number(v.split(' ')[0].slice(6)), 40 | y: Number(v.split(' ')[1].slice(0, -1)), 41 | }), 42 | to: (v) => `POINT(${v.x} ${v.y})`, 43 | }, 44 | }) 45 | @Index({ spatial: true }) 46 | @ApiProperty({ description: 'The current location of the aircraft' }) 47 | location: Point; 48 | 49 | @Column() 50 | @ApiProperty({ description: 'The altitude above sea level of the aircraft in feet', example: 3500 }) 51 | trueAltitude: number; 52 | 53 | @Column() 54 | @ApiProperty({ description: 'The heading the aircraft in degrees', example: 250.46, minimum: 0, maximum: 360 }) 55 | heading: number; 56 | 57 | @Column() 58 | @ApiProperty({ description: 'Whether the user wants to receive freetext messages', example: true }) 59 | freetextEnabled: boolean; 60 | 61 | @Column() 62 | @ApiProperty({ description: 'The aircraft type the connection associated with', example: 'A32NX' }) 63 | aircraftType?: string; 64 | 65 | @Column({ nullable: true }) 66 | @ApiProperty({ description: 'The origin of the flight', example: 'KLAX', required: false }) 67 | origin?: string; 68 | 69 | @Column({ nullable: true }) 70 | @ApiProperty({ description: 'The destination of the flight', example: 'KSFO', required: false }) 71 | destination?: string; 72 | } 73 | -------------------------------------------------------------------------------- /src/telex/entities/telex-message.entity.ts: -------------------------------------------------------------------------------- 1 | import { Column, CreateDateColumn, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'; 2 | import { ApiProperty } from '@nestjs/swagger'; 3 | import { TelexConnection } from './telex-connection.entity'; 4 | 5 | @Entity() 6 | export class TelexMessage { 7 | @PrimaryGeneratedColumn('uuid') 8 | @ApiProperty({ description: 'The unique identifier of the message', example: '6571f19e-21f7-4080-b239-c9d649347101' }) 9 | id?: string; 10 | 11 | @CreateDateColumn() 12 | @ApiProperty({ description: 'The time the message was sent' }) 13 | createdAt?: Date; 14 | 15 | @Column({ default: false }) 16 | @ApiProperty({ description: 'Whether the message has been received' }) 17 | received?: boolean; 18 | 19 | @Column() 20 | @ApiProperty({ description: 'The message to send', example: 'Hello over there!' }) 21 | message: string; 22 | 23 | @Column() 24 | @ApiProperty({ description: 'Whether the message contains profanity and got filtered' }) 25 | isProfane: boolean; 26 | 27 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 28 | @ManyToOne((type) => TelexConnection, (x) => x.id, { eager: true }) 29 | @ApiProperty({ description: 'The sender connection' }) 30 | from: TelexConnection; 31 | 32 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 33 | @ManyToOne((type) => TelexConnection, (x) => x.id, { eager: true }) 34 | @ApiProperty({ description: 'The recipient connection' }) 35 | to: TelexConnection; 36 | } 37 | -------------------------------------------------------------------------------- /src/telex/filters.ts: -------------------------------------------------------------------------------- 1 | export const BannedFlightNumbers = [ 2 | 'DISPATCH', 3 | 'DISPATCHER', 4 | 'FBW', 5 | 'FBWTEAM', 6 | 'FLYBYWIRE', 7 | 'SYSTEM', 8 | 'MSFS', 9 | 'ATC', 10 | 'GROUND', 11 | 'VATSIM', 12 | 'IVAO', 13 | 'PILOTEDGE', 14 | 'PILOT EDGE', 15 | 'POSCON', 16 | 'AAL11', 17 | 'AA11', 18 | 'UAL93', 19 | 'UA93', 20 | 'AAL77', 21 | 'AA77', 22 | 'MAS17', 23 | 'MH17', 24 | 'MAS370', 25 | 'MH370', 26 | 'UAL175', 27 | 'UA175', 28 | 'AF447', 29 | 'MSR990', 30 | 'MSR804', 31 | 'SJ182', 32 | 'SJY182', 33 | ]; 34 | 35 | export const BlockedMessageFilters = [ 36 | // Frequent spam 37 | 'LDS.ORG', 38 | 'LDSORG', 39 | 'COMEUNTOCHRIST', 40 | 'COME UNTO CHRIST', 41 | 'BOOKOFMORMON', 42 | 'BOOK OF MORMON', 43 | 'CHURCHOFJESUSCHRIST', 44 | 'JESUS', 45 | 'CHRIST', 46 | 'CHURCH', 47 | 'ALLAH', 48 | 'GOD', 49 | // Common TLD's 50 | '.COM', 51 | '.ORG', 52 | '.NET', 53 | '.IO', 54 | '. COM', 55 | '. ORG', 56 | '. NET', 57 | '. IO', 58 | // Tiny URLs 59 | 'RB.GY', 60 | 'CUTT.LY', 61 | 'BIT.LY', 62 | ]; 63 | -------------------------------------------------------------------------------- /src/telex/telex-connection.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, CacheInterceptor, CacheTTL, 3 | Controller, 4 | Delete, 5 | Get, 6 | Param, 7 | Post, 8 | Put, 9 | Query, 10 | Request, 11 | UseGuards, UseInterceptors, 12 | ValidationPipe, 13 | } from '@nestjs/common'; 14 | import { 15 | ApiBadRequestResponse, 16 | ApiBody, 17 | ApiCreatedResponse, 18 | ApiNotFoundResponse, 19 | ApiOkResponse, 20 | ApiParam, ApiQuery, ApiSecurity, 21 | ApiTags, 22 | } from '@nestjs/swagger'; 23 | import { TelexConnection } from './entities/telex-connection.entity'; 24 | import { TelexService } from './telex.service'; 25 | import { FlightToken } from '../auth/flights/flight-token.class'; 26 | import { FlightAuthGuard } from '../auth/flights/flight-auth-guard.service'; 27 | import { BoundsDto } from '../common/Bounds'; 28 | import { PaginationDto } from '../common/Pagination'; 29 | import { PaginatedTelexConnectionDto } from './dto/paginated-telex-connection.dto'; 30 | import { TelexSearchResult } from './dto/telex-search-result.dto'; 31 | import { CreateTelexConnectionDto } from './dto/create-telex-connection.dto'; 32 | import { UpdateTelexConnectionDto } from './dto/update-telex-connection.dto'; 33 | 34 | @ApiTags('TELEX') 35 | @Controller('txcxn') 36 | @UseInterceptors(CacheInterceptor) 37 | export class TelexConnectionController { 38 | constructor(private telex: TelexService) { 39 | } 40 | 41 | @Get() 42 | @CacheTTL(15) 43 | @ApiOkResponse({ description: 'The paginated list of connections', type: PaginatedTelexConnectionDto }) 44 | @ApiQuery({ 45 | name: 'take', 46 | type: Number, 47 | required: false, 48 | description: 'The number of connections to take', 49 | schema: { maximum: 25, minimum: 0, default: 25 }, 50 | }) 51 | @ApiQuery({ 52 | name: 'skip', 53 | type: Number, 54 | required: false, 55 | description: 'The number of connections to skip', 56 | schema: { minimum: 0, default: 0 }, 57 | }) 58 | @ApiQuery({ 59 | name: 'north', 60 | type: Number, 61 | required: false, 62 | description: 'Latitude for the north edge of the bounding box', 63 | schema: { minimum: -90, maximum: 90, default: 90 }, 64 | }) 65 | @ApiQuery({ 66 | name: 'east', 67 | type: Number, 68 | required: false, 69 | description: 'Longitude for the east edge of the bounding box', 70 | schema: { minimum: -180, maximum: 180, default: 180 }, 71 | }) 72 | @ApiQuery({ 73 | name: 'south', 74 | type: Number, 75 | required: false, 76 | description: 'Latitude for the south edge of the bounding box', 77 | schema: { minimum: -90, maximum: 90, default: -90 }, 78 | }) 79 | @ApiQuery({ 80 | name: 'west', 81 | type: Number, 82 | required: false, 83 | description: 'Longitude for the west edge of the bounding box', 84 | schema: { minimum: -180, maximum: 180, default: -180 }, 85 | }) 86 | getAllActiveConnections(@Query(new ValidationPipe({ transform: true })) pagination: PaginationDto, 87 | @Query(new ValidationPipe({ transform: true })) bounds: BoundsDto): Promise { 88 | return this.telex.getActiveConnections(pagination, bounds); 89 | } 90 | 91 | @Get('_find') 92 | @CacheTTL(15) 93 | @ApiQuery({ name: 'flight', description: 'The flight number', example: 'AAL456' }) 94 | @ApiOkResponse({ description: 'All connections matching the query', type: TelexSearchResult }) 95 | findConnection(@Query('flight') flight: string): Promise { 96 | return this.telex.findActiveConnectionByFlight(flight); 97 | } 98 | 99 | @Get('_count') 100 | @CacheTTL(15) 101 | @ApiOkResponse({ description: 'The total number of active flights', type: Number }) 102 | countConnections(): Promise { 103 | return this.telex.countActiveConnections(); 104 | } 105 | 106 | @Get(':id') 107 | @CacheTTL(15) 108 | @ApiParam({ name: 'id', description: 'The connection ID', example: '6571f19e-21f7-4080-b239-c9d649347101' }) 109 | @ApiOkResponse({ description: 'The connection with the given ID was found', type: TelexConnection }) 110 | @ApiNotFoundResponse({ description: 'The connection with the given ID could not be found' }) 111 | getSingleConnection(@Param('id') id: string): Promise { 112 | return this.telex.getSingleConnection(id); 113 | } 114 | 115 | @Post() 116 | @ApiBody({ 117 | description: 'The new connection containing the flight number and current location', 118 | type: CreateTelexConnectionDto, 119 | }) 120 | @ApiCreatedResponse({ description: 'A flight got created', type: FlightToken }) 121 | @ApiBadRequestResponse({ description: 'An active flight with the given flight number is already in use' }) 122 | addNewConnection(@Body() body: CreateTelexConnectionDto): Promise { 123 | return this.telex.addNewConnection(body); 124 | } 125 | 126 | @Put() 127 | @UseGuards(FlightAuthGuard) 128 | @ApiSecurity('jwt') 129 | @ApiBody({ description: 'The updated connection containing the current location', type: UpdateTelexConnectionDto }) 130 | @ApiOkResponse({ description: 'The connection got updated', type: TelexConnection }) 131 | @ApiNotFoundResponse({ description: 'The connection with the given ID could not be found' }) 132 | updateConnection(@Body() body: UpdateTelexConnectionDto, @Request() req): Promise { 133 | return this.telex.updateConnection(req.user.connectionId, body); 134 | } 135 | 136 | @Delete() 137 | @UseGuards(FlightAuthGuard) 138 | @ApiSecurity('jwt') 139 | @ApiOkResponse({ description: 'The connection got disabled' }) 140 | @ApiNotFoundResponse({ description: 'The connection with the given ID could not be found' }) 141 | disableConnection(@Request() req): Promise { 142 | return this.telex.disableConnection(req.user.connectionId); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /src/telex/telex-message.controller.ts: -------------------------------------------------------------------------------- 1 | import { Body, Controller, Get, Post, Request, UseGuards } from '@nestjs/common'; 2 | import { 3 | ApiBody, 4 | ApiCreatedResponse, 5 | ApiNotFoundResponse, 6 | ApiOkResponse, ApiSecurity, 7 | ApiTags, 8 | } from '@nestjs/swagger'; 9 | import { TelexService } from './telex.service'; 10 | import { TelexMessage } from './entities/telex-message.entity'; 11 | import { FlightAuthGuard } from '../auth/flights/flight-auth-guard.service'; 12 | import { TelexMessageDto } from './dto/telex-message.dto'; 13 | import { IpAddress } from '../utilities/ip-address.decorator'; 14 | 15 | @ApiTags('TELEX') 16 | @Controller('txmsg') 17 | export class TelexMessageController { 18 | constructor(private telex: TelexService) { 19 | } 20 | 21 | @Post() 22 | @UseGuards(FlightAuthGuard) 23 | @ApiSecurity('jwt') 24 | @ApiBody({ description: 'The message to send', type: TelexMessageDto }) 25 | @ApiCreatedResponse({ description: 'The message could be addressed', type: TelexMessage }) 26 | @ApiNotFoundResponse({ description: 'The sender or recipient flight number could not be found' }) 27 | async sendNewMessage(@Body() body: TelexMessageDto, @Request() req, @IpAddress() userIp): Promise { 28 | return this.telex.sendMessage(body, req.user.connectionId, userIp); 29 | } 30 | 31 | @Get() 32 | @UseGuards(FlightAuthGuard) 33 | @ApiSecurity('jwt') 34 | @ApiOkResponse({ description: 'Open messages for the recipient. Will get automatically acknowledged', type: [TelexMessage] }) 35 | async getMessagesForConnection(@Request() req): Promise { 36 | return this.telex.fetchMyMessages(req.user.connectionId, true); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/telex/telex.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TelexConnectionController } from './telex-connection.controller'; 3 | 4 | describe('TelexController', () => { 5 | let controller: TelexConnectionController; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ controllers: [TelexConnectionController] }).compile(); 9 | 10 | controller = module.get(TelexConnectionController); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(controller).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/telex/telex.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { TypeOrmModule } from '@nestjs/typeorm'; 3 | import { TelexConnection } from './entities/telex-connection.entity'; 4 | import { TelexService } from './telex.service'; 5 | import { TelexConnectionController } from './telex-connection.controller'; 6 | import { TelexMessage } from './entities/telex-message.entity'; 7 | import { TelexMessageController } from './telex-message.controller'; 8 | import { AuthModule } from '../auth/auth.module'; 9 | import { DiscordModule } from '../discord/discord.module'; 10 | import { BlockedIp } from './entities/blocked-ip.entity'; 11 | 12 | @Module({ 13 | imports: [ 14 | TypeOrmModule.forFeature([TelexConnection, TelexMessage, BlockedIp]), 15 | AuthModule, 16 | DiscordModule, 17 | ], 18 | providers: [TelexService], 19 | controllers: [TelexConnectionController, TelexMessageController], 20 | exports: [TelexService], 21 | }) 22 | export class TelexModule {} 23 | -------------------------------------------------------------------------------- /src/telex/telex.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { TelexService } from './telex.service'; 3 | 4 | describe('TelexService', () => { 5 | let service: TelexService; 6 | 7 | beforeEach(async () => { 8 | const module: TestingModule = await Test.createTestingModule({ providers: [TelexService] }).compile(); 9 | 10 | service = module.get(TelexService); 11 | }); 12 | 13 | it('should be defined', () => { 14 | expect(service).toBeDefined(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/telex/telex.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpException, Injectable, Logger } from '@nestjs/common'; 2 | import { Connection, Repository } from 'typeorm'; 3 | import { InjectRepository } from '@nestjs/typeorm'; 4 | import * as Filter from 'bad-words'; 5 | import { Cron } from '@nestjs/schedule'; 6 | import { ConfigService } from '@nestjs/config'; 7 | import { TelexConnection } from './entities/telex-connection.entity'; 8 | import { TelexMessage } from './entities/telex-message.entity'; 9 | import { AuthService } from '../auth/auth.service'; 10 | import { FlightToken } from '../auth/flights/flight-token.class'; 11 | import { BannedFlightNumbers, BlockedMessageFilters } from './filters'; 12 | import { BoundsDto } from '../common/Bounds'; 13 | import { PaginationDto } from '../common/Pagination'; 14 | import { CreateTelexConnectionDto } from './dto/create-telex-connection.dto'; 15 | import { UpdateTelexConnectionDto } from './dto/update-telex-connection.dto'; 16 | import { PaginatedTelexConnectionDto } from './dto/paginated-telex-connection.dto'; 17 | import { TelexSearchResult } from './dto/telex-search-result.dto'; 18 | import { TelexMessageDto } from './dto/telex-message.dto'; 19 | import { DiscordService } from '../discord/discord.service'; 20 | import { BlockedIp } from './entities/blocked-ip.entity'; 21 | 22 | @Injectable() 23 | export class TelexService { 24 | private readonly logger = new Logger(TelexService.name); 25 | 26 | private readonly profanityFilter; 27 | 28 | constructor( 29 | private connection: Connection, 30 | @InjectRepository(TelexConnection) 31 | private readonly connectionRepository: Repository, 32 | @InjectRepository(TelexMessage) 33 | private readonly messageRepository: Repository, 34 | @InjectRepository(BlockedIp) 35 | private readonly blockedIpRepository: Repository, 36 | private readonly configService: ConfigService, 37 | private readonly authService: AuthService, 38 | private readonly discordService: DiscordService, 39 | ) { 40 | this.profanityFilter = new Filter(); 41 | } 42 | 43 | @Cron('*/5 * * * * *') 44 | private async checkForStaleConnections() { 45 | if (this.configService.get('telex.disableCleanup')) { 46 | return; 47 | } 48 | 49 | const timeout = this.configService.get('telex.timeoutMin'); 50 | this.logger.verbose(`Trying to cleanup stale TELEX connections older than ${timeout} minutes`); 51 | 52 | const connections = await this.connectionRepository 53 | .createQueryBuilder() 54 | .update() 55 | .set({ isActive: false }) 56 | .andWhere(`lastContact < NOW() - INTERVAL ${timeout} MINUTE`) 57 | .andWhere('isActive = 1') 58 | .execute(); 59 | 60 | this.logger.debug(`Set ${connections.affected} stale connections to inactive`); 61 | } 62 | 63 | // ======= Connection Handling ======= // 64 | 65 | async addNewConnection(connection: CreateTelexConnectionDto): Promise { 66 | this.logger.log(`Trying to register new flight '${connection.flight}'`); 67 | 68 | if (BannedFlightNumbers.includes(connection.flight.toUpperCase())) { 69 | const message = `User tried to use banned flight number: '${connection.flight}'`; 70 | this.logger.log(message); 71 | throw new HttpException(message, 400); 72 | } 73 | 74 | const existingFlight = await this.connectionRepository.findOne({ flight: connection.flight, isActive: true }); 75 | 76 | if (existingFlight) { 77 | const message = `An active flight with the number '${connection.flight}' is already in use`; 78 | this.logger.error(message); 79 | throw new HttpException(message, 409); 80 | } 81 | 82 | const newFlight: TelexConnection = { ...connection }; 83 | 84 | this.logger.log(`Registering new flight '${connection.flight}'`); 85 | await this.connectionRepository.save(newFlight); 86 | 87 | return this.authService.registerFlight(newFlight.flight, newFlight.id); 88 | } 89 | 90 | async updateConnection(connectionId: string, connection: UpdateTelexConnectionDto): Promise { 91 | this.logger.log(`Trying to update flight with ID '${connectionId}'`); 92 | 93 | const change = await this.connectionRepository.update({ id: connectionId, isActive: true }, connection); 94 | 95 | if (!change.affected) { 96 | const message = `Active flight with ID '${connectionId}' does not exist`; 97 | this.logger.error(message); 98 | throw new HttpException(message, 404); 99 | } 100 | 101 | this.logger.log(`Updated flight with id '${connectionId}'`); 102 | return this.connectionRepository.findOne(connectionId); 103 | } 104 | 105 | async getActiveConnections(pagination: PaginationDto, bounds: BoundsDto): Promise { 106 | this.logger.log(`Trying to get ${pagination.take} TELEX connections, skipped ${pagination.skip}`); 107 | 108 | const [results, total] = await this.connectionRepository 109 | .createQueryBuilder() 110 | .select() 111 | .skip(pagination.skip) 112 | .take(pagination.take) 113 | .where({ isActive: true }) 114 | .andWhere( 115 | `ST_Contains(ST_MakeEnvelope(ST_GeomFromText('POINT(${bounds.west} ${bounds.north})'),` 116 | + ` ST_GeomFromText('POINT(${bounds.east} ${bounds.south})')), location)`, 117 | ) 118 | .orderBy('firstContact', 'ASC') 119 | .getManyAndCount(); 120 | 121 | return { 122 | results, 123 | count: results.length, 124 | total, 125 | }; 126 | } 127 | 128 | async countActiveConnections(): Promise { 129 | this.logger.debug('Trying to get total number of active connections'); 130 | 131 | return this.connectionRepository.count({ isActive: true }); 132 | } 133 | 134 | async getSingleConnection(id: string, active?: boolean): Promise { 135 | this.logger.log(`Trying to get single active TELEX connection with ID '${id}'`); 136 | 137 | const conn = await this.connectionRepository.findOne(id); 138 | if (!conn || (active !== undefined && conn.isActive !== active)) { 139 | const message = `${active ? 'Active f' : 'F'}light with ID '${id}' does not exist`; 140 | this.logger.error(message); 141 | throw new HttpException(message, 404); 142 | } 143 | 144 | return conn; 145 | } 146 | 147 | // TODO: Integrate with ORM to have all properties be searchable 148 | async findActiveConnectionByFlight(query: string): Promise { 149 | this.logger.log(`Trying to search for active TELEX connections with flight number '${query}'`); 150 | 151 | const matches = await this.connectionRepository 152 | .createQueryBuilder() 153 | .select() 154 | .andWhere(`UPPER(flight) LIKE UPPER('${query}%')`) 155 | .andWhere('isActive = 1') 156 | .orderBy('flight', 'ASC') 157 | .limit(50) 158 | .getMany(); 159 | 160 | return { 161 | matches, 162 | fullMatch: matches.find((x) => x.flight === query) ?? null, 163 | }; 164 | } 165 | 166 | async disableConnection(connectionId: string): Promise { 167 | this.logger.log(`Trying to disable TELEX connection with ID '${connectionId}'`); 168 | 169 | const existingFlight = await this.connectionRepository.findOne({ id: connectionId, isActive: true }); 170 | 171 | if (!existingFlight) { 172 | const message = `Active flight with ID '${connectionId}' does not exist`; 173 | this.logger.error(message); 174 | throw new HttpException(message, 404); 175 | } 176 | 177 | this.logger.log(`Disabling flight with ID '${connectionId}'`); 178 | existingFlight.isActive = false; 179 | 180 | await this.connectionRepository.update(existingFlight.id, existingFlight); 181 | } 182 | 183 | // ======= Message Handling ======= // 184 | 185 | async sendMessage(dto: TelexMessageDto, fromConnectionId: string, userIp: string): Promise { 186 | this.logger.log(`Trying to send a message from flight with ID '${fromConnectionId}' to flight with number ${dto.to}`); 187 | 188 | const sender = await this.getSingleConnection(fromConnectionId, true); 189 | if (!sender) { 190 | const message = `Active flight with ID '${fromConnectionId}' does not exist`; 191 | this.logger.error(message); 192 | throw new HttpException(message, 404); 193 | } 194 | 195 | const recipient = await this.connectionRepository.findOne({ flight: dto.to, isActive: true }); 196 | if (!recipient || !recipient.freetextEnabled) { 197 | const message = `Active flight '${dto.to}' does not exist`; 198 | this.logger.error(message); 199 | throw new HttpException(message, 404); 200 | } 201 | 202 | const message: TelexMessage = { 203 | from: sender, 204 | to: recipient, 205 | message: dto.message, 206 | isProfane: this.profanityFilter.isProfane(dto.message), 207 | }; 208 | 209 | // Check for blocked content. This implementation is somehow more resilient than `bad-words` 210 | const blockedContent = BlockedMessageFilters.some((str) => dto.message.toLowerCase().includes(str.toLowerCase())); 211 | // Check for an existing IP ban 212 | const blockedIp = await this.blockedIpRepository.findOne({ ip: userIp, isActive: true }); 213 | // Check if message is being sent to oneself. If it is, disable shadow blocking so people don't try to reverse engineer the filter. 214 | const sendingToSelf = sender.flight === dto.to; 215 | 216 | // No need to await this 217 | this.discordService.publishTelexMessage(message, blockedContent, !!blockedIp).then().catch(this.logger.error); 218 | 219 | if (blockedContent) { 220 | this.logger.warn(`Message with blocked content received: '${dto.message}' by ${sender.flight} (${sender.id})`); 221 | } 222 | 223 | if (blockedIp) { 224 | this.logger.warn(`Message from blocked IP '${blockedIp.ip}' received: '${dto.message}' by ${sender.flight} (${sender.id})`); 225 | } 226 | 227 | if ((blockedContent || blockedIp) && !sendingToSelf) { 228 | // Shadow blocking 229 | message.received = true; 230 | } 231 | 232 | this.logger.log(`Sending a message from flight with ID '${fromConnectionId}' to flight with number ${dto.to}`); 233 | const storedMessage = await this.messageRepository.save(message); 234 | 235 | // Shadow blocking 236 | storedMessage.received = false; 237 | return storedMessage; 238 | } 239 | 240 | async fetchMyMessages(connectionId: string, 241 | acknowledge: boolean): Promise { 242 | this.logger.log(`Trying to fetch TELEX messages for flight with ID '${connectionId}'`); 243 | 244 | const messages = await this.messageRepository.find({ to: { id: connectionId }, received: false }); 245 | 246 | if (!messages) { 247 | const message = `Error while fetching TELEX messages for flight with ID '${connectionId}'`; 248 | this.logger.log(message); 249 | throw new HttpException(message, 500); 250 | } 251 | 252 | if (acknowledge && messages.length > 0) { 253 | this.logger.log(`Acknowledging ${messages.length} TELEX messages for flight with ID '${connectionId}'`); 254 | 255 | await this.messageRepository.update({ to: { id: connectionId }, received: false }, { received: true }); 256 | } 257 | 258 | messages.forEach((msg) => { 259 | msg.message = this.profanityFilter.clean(msg.message); 260 | }); 261 | 262 | return messages; 263 | } 264 | } 265 | -------------------------------------------------------------------------------- /src/utilities/db-naming.ts: -------------------------------------------------------------------------------- 1 | import { DefaultNamingStrategy, Table, NamingStrategyInterface } from 'typeorm'; 2 | 3 | export class FbwNamingStrategy extends DefaultNamingStrategy implements NamingStrategyInterface { 4 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 5 | foreignKeyName(tableOrName: Table | string, columnNames: string[], referencedTablePath?: string, referencedColumnNames?: string[]): string { 6 | tableOrName = typeof tableOrName === 'string' ? tableOrName : tableOrName.name; 7 | 8 | const name = columnNames.reduce( 9 | (name, column) => `${name}_${column}`, 10 | `${tableOrName}_${referencedTablePath}`, 11 | ); 12 | 13 | return `fk_${name}`; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/utilities/ip-address.decorator.ts: -------------------------------------------------------------------------------- 1 | import { createParamDecorator, ExecutionContext } from '@nestjs/common'; 2 | 3 | import * as requestIp from 'request-ip'; 4 | 5 | export const IpAddress = createParamDecorator((data: unknown, ctx: ExecutionContext) => { 6 | const request = ctx.switchToHttp().getRequest(); 7 | 8 | if (request.clientIp) return request.clientIp; 9 | return requestIp.getClientIp(request); // In case we forgot to include requestIp.mw() in main.ts 10 | }); 11 | -------------------------------------------------------------------------------- /src/utilities/ivao.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { map, tap } from 'rxjs/operators'; 3 | import { CacheService } from '../cache/cache.service'; 4 | 5 | interface Client { 6 | time: number; 7 | id: number; 8 | userId: number; 9 | callsign: string; 10 | serverId: string; 11 | softwareVersion: string; 12 | softwareTypeId: string; 13 | rating: number; 14 | lastTrack: { 15 | altitude: number; 16 | altitudeDifference: number; 17 | arrivalDistance: number | null; 18 | departureDistance: number | null; 19 | groundSpeed: number; 20 | heading: number; 21 | latitude: number; 22 | longitude: number; 23 | onGround: boolean; 24 | state: null; 25 | time: number; 26 | timestamp: string; 27 | transponder: number; 28 | transponderMode: string; 29 | }; 30 | atcSession: { 31 | frequency: number; 32 | position: string; 33 | }; 34 | createdAt: string; 35 | } 36 | 37 | interface Server { 38 | id: string; 39 | hostname: string; 40 | ip: string; 41 | description: string; 42 | countryId: string; 43 | currentConnections: number; 44 | maximumConnections: number; 45 | } 46 | 47 | interface Atis { 48 | lines: string[]; 49 | callsign: string; 50 | revision: number; 51 | timestamp: string; 52 | sessionId: number; 53 | } 54 | 55 | interface Whazzup { 56 | updatedAt: string; 57 | servers: Server[]; 58 | voiceServers: Server[]; 59 | clients: { 60 | atcs: Client[]; 61 | followMe: unknown[]; 62 | observers: Client[]; 63 | pilots: Client[]; 64 | }; 65 | connections: { 66 | atc: number; 67 | observer: number; 68 | pilot: number; 69 | supervisor: number; 70 | total: number; 71 | worldTour: number; 72 | }; 73 | } 74 | 75 | interface AtisMergedWhazzup extends Whazzup { 76 | clients: { 77 | atcs: (Client & { atis?: Atis })[]; 78 | followMe: unknown[]; 79 | observers: Client[]; 80 | pilots: Client[]; 81 | } 82 | } 83 | 84 | type WhazzupAtis = Atis[]; 85 | 86 | @Injectable() 87 | export class IvaoService { 88 | private readonly logger = new Logger(IvaoService.name); 89 | 90 | constructor( 91 | private http: HttpService, 92 | private readonly cache: CacheService, 93 | ) {} 94 | 95 | public async fetchIvaoData(): Promise { 96 | const cacheHit = await this.cache.get('/ivao/data'); 97 | 98 | if (cacheHit) { 99 | this.logger.debug('Returning from cache'); 100 | return cacheHit; 101 | } 102 | 103 | const whazzupData: Whazzup = await this.http.get('https://api.ivao.aero/v2/tracker/whazzup') 104 | .pipe( 105 | tap((response) => this.logger.debug(`Response status ${response.status} for IVAO request`)), 106 | tap((response) => this.logger.debug(`Response contains ${response.data.length} entries`)), 107 | map((response) => response.data), 108 | ).toPromise(); 109 | 110 | const whazzupAtisData: WhazzupAtis = await this.http.get('https://api.ivao.aero/v2/tracker/whazzup/atis') 111 | .pipe( 112 | tap((response) => this.logger.debug(`Response status ${response.status} for IVAO request`)), 113 | tap((response) => this.logger.debug(`Response contains ${response.data.length} entries`)), 114 | map((response) => response.data), 115 | ).toPromise(); 116 | 117 | for (const atis of whazzupAtisData) { 118 | const atcWithSameCallsign = (whazzupData as AtisMergedWhazzup).clients.atcs.find((atcs) => atcs.callsign === atis.callsign); 119 | 120 | if (atcWithSameCallsign) { 121 | atcWithSameCallsign.atis = atis; 122 | } 123 | } 124 | 125 | this.cache.set('/ivao/data', whazzupData, 120).then(); 126 | return whazzupData; 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /src/utilities/not-found.filter.ts: -------------------------------------------------------------------------------- 1 | import { ArgumentsHost, Catch, ExceptionFilter, Logger, NotFoundException } from '@nestjs/common'; 2 | 3 | @Catch(NotFoundException) 4 | export class NotFoundExceptionFilter implements ExceptionFilter { 5 | private readonly logger = new Logger(NotFoundExceptionFilter.name); 6 | 7 | catch(exception: NotFoundException, host: ArgumentsHost) { 8 | const ctx = host.switchToHttp(); 9 | const response = ctx.getResponse(); 10 | const request = ctx.getRequest(); 11 | const status = exception.getStatus(); 12 | 13 | this.logger.log(`404 '${request.url}' '${JSON.stringify(request.headers)}'`); 14 | 15 | response 16 | // @ts-ignore 17 | .status(status) 18 | .json({ 19 | statusCode: status, 20 | timestamp: new Date().toISOString(), 21 | path: request.url, 22 | }); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/utilities/vatsim.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpService, Injectable, Logger } from '@nestjs/common'; 2 | import { map, tap } from 'rxjs/operators'; 3 | import { CacheService } from '../cache/cache.service'; 4 | 5 | @Injectable() 6 | export class VatsimService { 7 | private readonly logger = new Logger(VatsimService.name); 8 | 9 | constructor( 10 | private http: HttpService, 11 | private readonly cache: CacheService, 12 | ) {} 13 | 14 | public async fetchVatsimData(): Promise { 15 | const cacheHit = await this.cache.get('/vatsim/data'); 16 | 17 | if (cacheHit) { 18 | this.logger.debug('Returning from cache'); 19 | return cacheHit; 20 | } 21 | const data = await this.http.get('https://data.vatsim.net/v3/vatsim-data.json') 22 | .pipe( 23 | tap((response) => this.logger.debug(`Response status ${response.status} for VATSIM request`)), 24 | map((response) => response.data), 25 | ).toPromise(); 26 | 27 | this.cache.set('/vatsim/data', data, 120).then(); 28 | return data; 29 | } 30 | 31 | public async fetchVatsimTransceivers(): Promise { 32 | const cacheHit = await this.cache.get('/vatsim/transceivers'); 33 | 34 | if (cacheHit) { 35 | this.logger.debug('Returning from cache'); 36 | return cacheHit; 37 | } 38 | const data = await this.http.get('https://data.vatsim.net/v3/transceivers-data.json') 39 | .pipe( 40 | tap((response) => this.logger.debug(`Response status ${response.status} for VATSIM request`)), 41 | map((response) => response.data), 42 | ).toPromise(); 43 | 44 | this.cache.set('/vatsim/transceivers', data, 120).then(); 45 | return data; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from '../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile(); 11 | 12 | app = moduleFixture.createNestApplication(); 13 | await app.init(); 14 | }); 15 | 16 | it('/ (GET)', () => request(app.getHttpServer()) 17 | .get('/') 18 | .expect(200) 19 | .expect('Hello World!')); 20 | }); 21 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true 14 | } 15 | } 16 | --------------------------------------------------------------------------------