├── .github
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
└── workflows
│ ├── lint.yml
│ ├── release.yml
│ └── test.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── LICENSES
└── Apache-2.0.txt
├── README.md
├── REUSE.toml
├── cds-plugin.js
├── eslint.config.mjs
├── etc
├── delete.gif
├── facet.png
└── upload.gif
├── index.cds
├── jest.config.js
├── lib
├── aws-s3.js
├── basic.js
├── helper.js
├── malwareScanner.js
├── mtx
│ └── server.js
└── plugin.js
├── package.json
├── tests
├── incidents-app
│ ├── app
│ │ ├── incidents
│ │ │ ├── annotations.cds
│ │ │ ├── package.json
│ │ │ ├── ui5.yaml
│ │ │ └── webapp
│ │ │ │ ├── i18n
│ │ │ │ └── i18n.properties
│ │ │ │ ├── index.html
│ │ │ │ ├── manifest.json
│ │ │ │ └── xs-app.json
│ │ └── services.cds
│ ├── db
│ │ ├── attachments.cds
│ │ ├── data
│ │ │ ├── sap.capire.incidents-Addresses.csv
│ │ │ ├── sap.capire.incidents-Customers.csv
│ │ │ ├── sap.capire.incidents-Incidents.conversation.csv
│ │ │ ├── sap.capire.incidents-Incidents.csv
│ │ │ ├── sap.capire.incidents-Status.csv
│ │ │ └── sap.capire.incidents-Urgency.csv
│ │ └── schema.cds
│ ├── package.json
│ └── srv
│ │ ├── services.cds
│ │ └── services.js
├── integration
│ ├── attachments-non-draft.test.js
│ ├── attachments.test.js
│ └── content
│ │ ├── sample-1.jpg
│ │ ├── sample-2.txt
│ │ └── sample.pdf
├── non-draft-request.http
├── unit
│ └── validateAttachmentSize.test.js
└── utils
│ ├── api.js
│ └── modify-annotation.js
└── xmpl
├── .gitignore
├── README.md
├── db
├── attachments.cds
├── content
│ ├── Broken Solar Panel.jpg
│ ├── INVERTER FAULT REPORT.pdf
│ ├── Inverter-error-logs.txt
│ ├── No_current.xlsx
│ ├── Solar Panel Report.pdf
│ └── strange-noise.csv
└── init.js
├── package.json
└── srv
└── service.cds
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: "[Version: ] "
5 | labels: bug
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 |
16 | **Expected behavior**
17 | A clear and concise description of what you expected to happen.
18 |
19 | [ ] is it a regression issue?
20 |
21 | **Screenshots**
22 | If applicable, add screenshots to help explain your problem.
23 |
24 | **Customer Info**
25 | Company: xyz.
26 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: enhancement
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
22 | **Have you already checked existing issues before creating a feature request?**
23 | If you find same feature requests reported, upvote the issue (+1)
24 |
25 | **Customer Info**
26 | Company: xyz
27 |
--------------------------------------------------------------------------------
/.github/workflows/lint.yml:
--------------------------------------------------------------------------------
1 | name: Lint
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | types: [opened, synchronize, reopened, auto_merge_enabled]
8 |
9 | concurrency:
10 | group: lint-${{ github.workflow }}-${{ github.head_ref || github.run_id }}
11 | cancel-in-progress: true
12 |
13 | jobs:
14 | lint:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/setup-node@v4
18 | - uses: actions/checkout@v4
19 | - run: npm i
20 | - run: npm run lint
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release
2 |
3 | on:
4 | workflow_dispatch:
5 |
6 | permissions:
7 | contents: write
8 |
9 | jobs:
10 |
11 | publish-npm:
12 | runs-on: ubuntu-latest
13 | environment: npm
14 | steps:
15 | - uses: actions/checkout@v4
16 | - uses: actions/setup-node@v4
17 | with:
18 | node-version: 20
19 | registry-url: https://registry.npmjs.org/
20 |
21 | - name: Run Tests
22 | run: |
23 | npm install
24 | npm run lint
25 | cd tests/incidents-app && npm install
26 | cd ../..
27 | npm run test
28 |
29 | - name: get-version
30 | id: package-version
31 | uses: martinbeentjes/npm-get-version-action@v1.2.3
32 | - name: Parse changelog
33 | id: parse-changelog
34 | uses: schwma/parse-changelog-action@v1.0.0
35 | with:
36 | version: '${{ steps.package-version.outputs.current-version }}'
37 | - name: Create a GitHub release
38 | uses: ncipollo/release-action@v1
39 | with:
40 | tag: 'v${{ steps.package-version.outputs.current-version }}'
41 | body: '${{ steps.parse-changelog.outputs.body }}'
42 | - run: npm publish --access public
43 | env:
44 | NODE_AUTH_TOKEN: ${{secrets.npm_token}}
45 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | workflow_dispatch:
5 | push:
6 | branches: [ main ]
7 | pull_request:
8 | branches: [ main ]
9 |
10 | jobs:
11 | test:
12 | runs-on: ubuntu-latest
13 | strategy:
14 | fail-fast: false
15 | matrix:
16 | node-version: [20.x, 18.x]
17 | steps:
18 | - uses: actions/checkout@v2
19 | - name: Use Node.js ${{ matrix.node-version }}
20 | uses: actions/setup-node@v2
21 | with:
22 | node-version: ${{ matrix.node-version }}
23 | - run: npm i -g @sap/cds-dk
24 | - run: npm i
25 | - run: cd tests/incidents-app && npm i
26 | - run: npm run test
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | .DS_Store
3 | node_modules/
4 | gen/
5 |
6 | package-lock.json
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 |
3 | All notable changes to this project will be documented in this file.
4 | This project adheres to [Semantic Versioning](http://semver.org/).
5 | The format is based on [Keep a Changelog](http://keepachangelog.com/).
6 |
7 | ## Version 2.1.2
8 |
9 | ### Fixed
10 |
11 | - Bug fixes.
12 |
13 | ## Version 2.1.1
14 |
15 | ### Added
16 |
17 | - MTX: Support for deleting tenant-specific objects from S3 upon tenant unsubscription in shared mode.
18 |
19 | ### Fixed
20 |
21 | - Deleted attachments are now removed from S3 when a draft is discarded or deleted.
22 |
23 | ## Version 2.1.0
24 |
25 | ### Added
26 |
27 | - Support for multitenancy with tenant specific object store instances as the default option.
28 |
29 | ### Fixed
30 |
31 | - Support for `.mov` file extension.
32 |
33 | ## Version 2.0.2
34 |
35 | ### Fixed
36 |
37 | - Restored Attachments aspect on root namespace.
38 |
39 | ## Version 2.0.1
40 |
41 | ### Fixed
42 |
43 | - Minor bug fixes.
44 |
45 | ## Version 2.0.0
46 |
47 | ### Changed
48 |
49 | - Removed `@sap/xsenv` dependency.
50 | - Attachments usage changed to `using { sap.attachments.Attachments } from '@cap-js/attachments'`.
51 |
52 | ### Added
53 |
54 | - **Visibility Control**: Added visibility control for attachments plugin using `@attachments.disable_facet`.
55 |
56 | ## Version 1.2.1
57 |
58 | ### Fixed
59 |
60 | - CDS version check added for rendering UI facets in older versions.
61 |
62 | ## Version 1.2.0
63 |
64 | ### Added
65 |
66 | - Support for multi-tenant applications utilizing a shared `object store` instance.
67 |
68 | ### Fixed
69 |
70 | - Fixed query syntax error for hana cloud bindings.
71 |
72 | ## Version 1.1.9
73 |
74 | ### Added
75 |
76 | - **File Size Validation**: Introduced a new file size validation feature to ensure uploaded attachments comply with defined size limits.
77 | - This feature is compatible with SAPUI5 version `>= 1.131.0`.
78 |
79 | ### Fixed
80 |
81 | - Fixed upload attachment bug after cds `8.7.0` update.
82 |
83 | ## Version 1.1.8
84 |
85 | ### Changed
86 |
87 | - Included test cases for malware scanning within development profile.
88 |
89 | ### Fixed
90 |
91 | - Fix for viewing stored attachment.
92 |
93 | ## Version 1.1.7
94 |
95 | ### Fixed
96 |
97 | - Fix for scenario where an aspect has a composition.
98 |
99 | ## Version 1.1.6
100 |
101 | ### Added
102 |
103 | - Support for cds 8.
104 |
105 | ### Fixed
106 |
107 | - Fix for adding note for attachments.
108 |
109 | ## Version 1.1.5
110 |
111 | ### Changed
112 |
113 | - Set width for columns for Attachments table UI.
114 | - Scan status is mocked to `Clean` only in the development profile and otherwise set to `Unscanned`, when malware scan is disabled.
115 | - When malware scan is disabled, removed restriction to access uploaded attachment.
116 |
117 | ## Version 1.1.4
118 |
119 | ### Changed
120 |
121 | - Updated Node version restriction.
122 |
123 | ## Version 1.1.3
124 |
125 | ### Changed
126 |
127 | - Improved error handling.
128 |
129 | ### Fixed
130 |
131 | - Minor bug fixes.
132 |
133 | ## Version 1.1.2
134 |
135 | ### Added
136 |
137 | - Content of files detected as `Infected` from malware scanning service are now deleted.
138 |
139 | ### Changed
140 |
141 | - Attachments aren't served if their scan status isn't `Clean`.
142 | - Reduced the delay of setting scan status to `Clean` to 5 sec, if malware scanning is disabled.
143 |
144 | ### Fixed
145 |
146 | - Bug fixes for event handlers in production.
147 | - Bug fix for attachment target condition.
148 |
149 | ## Version 1.1.1
150 |
151 | ### Changed
152 |
153 | - Enabled malware scanning in hybrid profile by default.
154 | - Added a 10 sec delay before setting scan status to `Clean` if malware scanning is disabled.
155 |
156 | ### Fixed
157 |
158 | - Bug fixes for upload functionality in production.
159 |
160 | ## Version 1.1.0
161 |
162 | ### Added
163 |
164 | - Attachments are scanned for malware using SAP Malware Scanning Service.
165 |
166 | ### Fixed
167 |
168 | - Fixes for deployment
169 |
170 | ## Version 1.0.2
171 |
172 | ### Fixed
173 |
174 | - Bug fixes
175 |
176 | ## Version 1.0.1
177 |
178 | ### Fixed
179 |
180 | - Updating the documentation.
181 |
182 | ## Version 1.0.0
183 |
184 | ### Added
185 |
186 | - Initial release that provides out-of-the box asset storage and handling by using an aspect Attachments. It also provides a CAP-level, easy to use integration of the SAP Object Store.
187 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, caste, color, religion, or sexual
10 | identity and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the overall
26 | community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or advances of
31 | any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email address,
35 | without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | [INSERT CONTACT METHOD].
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series of
86 | actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or permanent
93 | ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within the
113 | community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.1, available at
119 | [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120 |
121 | Community Impact Guidelines were inspired by
122 | [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123 |
124 | For answers to common questions about this code of conduct, see the FAQ at
125 | [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126 | [https://www.contributor-covenant.org/translations][translations].
127 |
128 | [homepage]: https://www.contributor-covenant.org
129 | [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130 | [Mozilla CoC]: https://github.com/mozilla/diversity
131 | [FAQ]: https://www.contributor-covenant.org/faq
132 | [translations]: https://www.contributor-covenant.org/translations
133 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | ## Code of Conduct
4 |
5 | All members of the project community must abide by the [Contributor Covenant, version 2.1](CODE_OF_CONDUCT.md).
6 | Only by respecting each other we can develop a productive, collaborative community.
7 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting [a project maintainer](.reuse/dep5).
8 |
9 | ## Engaging in Our Project
10 |
11 | We use GitHub to manage reviews of pull requests.
12 |
13 | * If you are a new contributor, see: [Steps to Contribute](#steps-to-contribute)
14 |
15 | * Before implementing your change, create an issue that describes the problem you would like to solve or the code that should be enhanced. Please note that you are willing to work on that issue.
16 |
17 | * The team will review the issue and decide whether it should be implemented as a pull request. In that case, they will assign the issue to you. If the team decides against picking up the issue, the team will post a comment with an explanation.
18 |
19 | ## Steps to Contribute
20 |
21 | Should you wish to work on an issue, please claim it first by commenting on the GitHub issue that you want to work on. This is to prevent duplicated efforts from other contributors on the same issue.
22 |
23 | If you have questions about one of the issues, please comment on them, and one of the maintainers will clarify.
24 |
25 | ## Contributing Code or Documentation
26 |
27 | You are welcome to contribute code in order to fix a bug or to implement a new feature that is logged as an issue.
28 |
29 | The following rule governs code contributions:
30 |
31 | * Contributions must be licensed under the [Apache 2.0 License](./LICENSE)
32 | * Due to legal reasons, contributors will be asked to accept a Developer Certificate of Origin (DCO) when they create the first pull request to this project. This happens in an automated fashion during the submission process. SAP uses [the standard DCO text of the Linux Foundation](https://developercertificate.org/).
33 |
34 | ## Issues and Planning
35 |
36 | * We use GitHub issues to track bugs and enhancement requests.
37 |
38 | * Please provide as much context as possible when you open an issue. The information you provide must be comprehensive enough to reproduce that issue for the assignee.
39 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/LICENSES/Apache-2.0.txt:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
10 |
11 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
12 |
13 | "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
14 |
15 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
16 |
17 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
18 |
19 | "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
20 |
21 | "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
22 |
23 | "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
24 |
25 | "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
26 |
27 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
28 |
29 | 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
30 |
31 | 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
32 |
33 | 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
34 |
35 | (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
36 |
37 | (b) You must cause any modified files to carry prominent notices stating that You changed the files; and
38 |
39 | (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
40 |
41 | (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
42 |
43 | You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
44 |
45 | 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
46 |
47 | 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
48 |
49 | 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
50 |
51 | 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
52 |
53 | 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
54 |
55 | END OF TERMS AND CONDITIONS
56 |
57 | APPENDIX: How to apply the Apache License to your work.
58 |
59 | To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
60 |
61 | Copyright [yyyy] [name of copyright owner]
62 |
63 | Licensed under the Apache License, Version 2.0 (the "License");
64 | you may not use this file except in compliance with the License.
65 | You may obtain a copy of the License at
66 |
67 | http://www.apache.org/licenses/LICENSE-2.0
68 |
69 | Unless required by applicable law or agreed to in writing, software
70 | distributed under the License is distributed on an "AS IS" BASIS,
71 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
72 | See the License for the specific language governing permissions and
73 | limitations under the License.
74 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://api.reuse.software/info/github.com/cap-js/attachments)
2 |
3 | # Attachments Plugin
4 |
5 | The `@cap-js/attachments` package is a [CDS plugin](https://cap.cloud.sap/docs/node.js/cds-plugins#cds-plugin-packages) that provides out-of-the box asset storage and handling by using an *aspect* `Attachments`. It also provides a CAP-level, easy to use integration of the SAP Object Store.
6 |
7 | ### Table of Contents
8 |
9 | - [Setup](#setup)
10 | - [Use `Attachments`](#use-attachments)
11 | - [Test-drive Locally](#test-drive-locally)
12 | - [Using SAP Object Store](#using-sap-object-store)
13 | - [Using SAP Malware Scanning service](#using-sap-malware-scanning-service)
14 | - [Multitenancy](#multi-tenancy)
15 | - [Contributing](#contributing)
16 | - [Code of Conduct](#code-of-conduct)
17 | - [Licensing](#licensing)
18 |
19 |
20 | ## Setup
21 |
22 |
23 |
24 | To enable attachments, simply add this self-configuring plugin package to your project:
25 |
26 | ```sh
27 | npm add @cap-js/attachments
28 | ```
29 |
30 | In this guide, we use the [Incidents Management reference sample app](https://github.com/cap-js/incidents-app) as the base application, to add `Attachments` type to the CDS model.
31 |
32 | > [!Note]
33 | > To be able to use the Fiori *uploadTable* feature, you must ensure 1.121.0/ 1.122.0/ ^1.125.0 SAPUI5 version is updated in the application's _index.html_
34 |
35 |
36 | ## Use Attachments
37 |
38 | > [!Note]
39 | > To be able to use the plugin with Fiori elements UI, make sure *draft* is enabled for the entity.
40 |
41 | To use Attachments, simply add an element referring to the pre-defined `Attachments` type as follows:
42 |
43 | ```cds
44 | using { Attachments } from '@cap-js/attachments';
45 |
46 | entity Incidents {
47 | // ...
48 | attachments: Composition of many Attachments;
49 | }
50 | ```
51 |
52 |
53 | ## Test-drive Locally
54 | With the steps above, we have successfully set up asset handling for our reference application. Let's see that in action.
55 | We can try out the scenarios where the attachments contents are stored locally in the database.
56 |
57 | 1. **Start the server**:
58 |
59 | - *Default* scenario (In memory database):
60 | ```sh
61 | cds watch
62 | ```
63 |
64 | 2. **Navigate to the object page** of the incident `Solar panel broken`:
65 |
66 | Go to [Object page for incident **Solar panel broken**](http://localhost:4004/incidents/app/#/Incidents(ID=3583f982-d7df-4aad-ab26-301d4a157cd7,IsActiveEntity=true))
67 |
68 | 3. The `Attachments` type has generated an out-of-the-box Attachments table (see 1) at the bottom of the Object page:
69 |
70 |
71 | 4. **Upload a file** by going into Edit mode and either using the **Upload** button on the Attachments table or by drag/drop. Then click the **Save** button to have that file stored that file in the dedicated resource (database, S3 bucket, etc.). We demonstrate this by uploading the PDF file from [_xmpl/db/content/Solar Panel Report.pdf_](./xmpl/db/content/Solar%20Panel%20Report.pdf):
72 |
73 |
74 | 6. **Delete a file** by going into Edit mode and selecting the file(s) and by using the **Delete** button on the Attachments table. Then click the **Save** button to have that file deleted from the resource (database, S3 bucket, etc.). We demonstrate this by deleting the previously uploaded PDF file: `Solar Panel Report.pdf`
75 |
76 |
77 |
78 | ## Using SAP Object Store
79 |
80 | For using SAP Object Store, you must already have a SAP Object Store service instance with a bucket which you can access. To connect it, follow this setup.
81 |
82 | 1. Log in to Cloud Foundry:
83 |
84 | ```sh
85 | cf login -a -o -s
86 | ```
87 |
88 | 2. To bind to the service continue with the steps below.
89 |
90 | In the project directory, you can generate a new file _.cdsrc-private.json by running:
91 |
92 | ```sh
93 | cds bind objectstore -2 : --kind s3
94 | ```
95 |
96 | ## Using SAP Malware Scanning Service
97 |
98 | For using [SAP Malware Scanning Service](https://discovery-center.cloud.sap/serviceCatalog/malware-scanning-service), you must already have a service instance which you can access.
99 |
100 | 1. To bind to the service continue with the steps below.
101 |
102 | ```sh
103 | cds bind malware-scanner -2 :
104 | ```
105 |
106 | By default, malware scanning is enabled for all profiles except development profile. You can configure malware scanning by setting:
107 |
108 | ```json
109 | "attachments": {
110 | "scan": true
111 | }
112 | ```
113 |
114 |
115 | ## Visibility control for Attachments UI Facet generation
116 |
117 | By setting the `@attachments.disable_facet` property to `true`, developers can hide the plugin from the UI achieving visibility.
118 | This feature is particularly useful in scenarios where the visibility of the plugin needs to be dynamically controlled based on certain conditions.
119 |
120 | ### Example Usage
121 |
122 | ```cds
123 | entity Incidents {
124 | // ...
125 | @attachments.disable_facet
126 | attachments: Composition of many Attachments;
127 | }
128 | ```
129 | In this example, the `@attachments.disable_facet` is set to `true`, which means the plugin will be hidden by default.
130 |
131 | ## Multitenancy
132 |
133 | The plugin supports multitenancy scenarios, allowing both shared and tenant-specific object store instances.
134 |
135 | > [!Note]
136 | > Starting from version 2.1.0, separate mode for object store instances is the default setting for multitenancy. Currently, only the `S3-standard` plan of the object store offering is supported.
137 |
138 | For multitenant applications, make sure to include `@cap-js/attachments` in the dependencies of both the application-level and mtx/sidecar package.json files.
139 |
140 | ### Shared Object Store Instance
141 |
142 | > [!Note]
143 | > Ensure the shared object store instance is bound to the `mtx` application module before deployment.
144 |
145 | To configure a shared object store instance, modify both the package.json files as follows:
146 |
147 | ```json
148 | "cds": {
149 | "requires": {
150 | "attachments": {
151 | "objectStore": {
152 | "kind": "shared"
153 | }
154 | }
155 | }
156 | }
157 | ```
158 | To ensure tenant identification when using a shared object store instance, the plugin prefixes attachment URLs with the tenant ID.
159 |
160 | ## Contributing
161 |
162 | This project is open to feature requests/suggestions, bug reports etc. via [GitHub issues](https://github.com/cap-js/attachments/issues). Contribution and feedback are encouraged and always welcome. For more information about how to contribute, the project structure, as well as additional contribution information, see our [Contribution Guidelines](CONTRIBUTING.md).
163 |
164 | ## Code of Conduct
165 |
166 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone. By participating in this project, you agree to abide by its [Code of Conduct](CODE_OF_CONDUCT.md) at all times.
167 |
168 | ## Licensing
169 |
170 | Copyright 2024 SAP SE or an SAP affiliate company and contributors. Please see our [LICENSE](LICENSE) for copyright and license information. Detailed information including third-party components and their licensing/copyright information is available [via the REUSE tool](https://api.reuse.software/info/github.com/cap-js/attachmentstea).
171 |
--------------------------------------------------------------------------------
/REUSE.toml:
--------------------------------------------------------------------------------
1 | version = 1
2 | SPDX-PackageName = "attachments"
3 | SPDX-PackageSupplier = "The CAP team "
4 | SPDX-PackageDownloadLocation = "https://github.com/cap-js/attachments"
5 | SPDX-PackageComment = "The code in this project may include calls to APIs (\"API Calls\") of\n SAP or third-party products or services developed outside of this project\n (\"External Products\").\n \"APIs\" means application programming interfaces, as well as their respective\n specifications and implementing code that allows software to communicate with\n other software.\n API Calls to External Products are not licensed under the open source license\n that governs this project. The use of such API Calls and related External\n Products are subject to applicable additional agreements with the relevant\n provider of the External Products. In no event shall the open source license\n that governs this project grant any rights in or to any External Products,or\n alter, expand or supersede any terms of the applicable additional agreements.\n If you have a valid license agreement with SAP for the use of a particular SAP\n External Product, then you may make use of any API Calls included in this\n project's code for that SAP External Product, subject to the terms of such\n license agreement. If you do not have a valid license agreement for the use of\n a particular SAP External Product, then you may only make use of any API Calls\n in this project for that SAP External Product for your internal, non-productive\n and non-commercial test and evaluation of such API Calls. Nothing herein grants\n you any rights to use or access any SAP External Product, or provide any third\n parties the right to use of access any SAP External Product, through API Calls."
6 |
7 | [[annotations]]
8 | path = "**"
9 | precedence = "aggregate"
10 | SPDX-FileCopyrightText = "2024 SAP SE or an SAP affiliate company and attachments contributors."
11 | SPDX-License-Identifier = "Apache-2.0"
12 |
--------------------------------------------------------------------------------
/cds-plugin.js:
--------------------------------------------------------------------------------
1 | require('./lib/plugin')
2 |
3 | // Entry point for separate object store instance case
4 | require('./lib/mtx/server')
5 |
--------------------------------------------------------------------------------
/eslint.config.mjs:
--------------------------------------------------------------------------------
1 | import cds from '@sap/cds/eslint.config.mjs'
2 | export default [ ...cds ]
3 |
--------------------------------------------------------------------------------
/etc/delete.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/etc/delete.gif
--------------------------------------------------------------------------------
/etc/facet.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/etc/facet.png
--------------------------------------------------------------------------------
/etc/upload.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/etc/upload.gif
--------------------------------------------------------------------------------
/index.cds:
--------------------------------------------------------------------------------
1 |
2 | // The common root-level aspect used in applications like that:
3 | // using { Attachments } from '@cap-js/attachments'
4 | aspect Attachments : sap.attachments.Attachments {}
5 |
6 |
7 | using { managed, cuid } from '@sap/cds/common';
8 | context sap.attachments {
9 |
10 | aspect MediaData @(_is_media_data) {
11 | url : String;
12 | content : LargeBinary @title: 'Attachment'; // only for db-based services
13 | mimeType : String default 'application/octet-stream' @title: 'Media Type';
14 | filename : String @title: 'Filename';
15 | status : String @title: 'Scan Status' enum {
16 | Unscanned;
17 | Scanning;
18 | Infected;
19 | Clean;
20 | Failed;
21 | } default 'Unscanned';
22 | }
23 |
24 | aspect Attachments : cuid, managed, MediaData {
25 | note : String @title: 'Note';
26 | }
27 |
28 |
29 | // -- Fiori Annotations ----------------------------------------------------------
30 |
31 | annotate MediaData with @UI.MediaResource: { Stream: content } {
32 | content @Core.MediaType: mimeType @odata.draft.skip;
33 | mimeType @Core.IsMediaType;
34 | status @readonly;
35 | }
36 |
37 | annotate Attachments with @UI:{
38 | HeaderInfo: {
39 | TypeName: '{i18n>Attachment}',
40 | TypeNamePlural: '{i18n>Attachments}',
41 | },
42 | LineItem: [
43 | {Value: content, @HTML5.CssDefaults: {width: '30%'}},
44 | {Value: status, @HTML5.CssDefaults: {width: '10%'}},
45 | {Value: createdAt, @HTML5.CssDefaults: {width: '20%'}},
46 | {Value: createdBy, @HTML5.CssDefaults: {width: '15%'}},
47 | {Value: note, @HTML5.CssDefaults: {width: '25%'}}
48 | ]
49 | } {
50 | content
51 | @Core.ContentDisposition: { Filename: filename, Type: 'inline' }
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/jest.config.js:
--------------------------------------------------------------------------------
1 | const config = {
2 | testTimeout: 42222,
3 | testMatch: ['**/*.test.js']
4 | }
5 |
6 | module.exports = config
--------------------------------------------------------------------------------
/lib/aws-s3.js:
--------------------------------------------------------------------------------
1 | const { S3Client, GetObjectCommand, DeleteObjectCommand } = require('@aws-sdk/client-s3');
2 | const { Upload } = require("@aws-sdk/lib-storage");
3 | const { scanRequest } = require('./malwareScanner')
4 | const cds = require("@sap/cds");
5 | const utils = require('./helper.js')
6 | const DEBUG = cds.debug('attachments');
7 | const { SELECT } = cds.ql;
8 |
9 | const isMultitenacyEnabled = !!cds.env.requires.multitenancy;
10 | const objectStoreKind = cds.env.requires?.attachments?.objectStore?.kind;
11 | const separateObjectStore = isMultitenacyEnabled && objectStoreKind === "separate";
12 |
13 | const s3ClientsCache = {};
14 | module.exports = class AWSAttachmentsService extends require("./basic") {
15 | init() {
16 | // For single tenant or shared object store instance
17 | if (!separateObjectStore) {
18 | const creds = cds.env.requires?.objectStore?.credentials;
19 |
20 | if (!creds) throw new Error("SAP Object Store instance is not bound.");
21 |
22 | this.bucket = creds.bucket;
23 | this.client = new S3Client({
24 | region: creds.region,
25 | credentials: {
26 | accessKeyId: creds.access_key_id,
27 | secretAccessKey: creds.secret_access_key,
28 | },
29 | });
30 | return super.init();
31 | }
32 | }
33 |
34 | async createClientS3(tenantID) {
35 | try {
36 | if (s3ClientsCache[tenantID]) {
37 | this.client = s3ClientsCache[tenantID].client;
38 | this.bucket = s3ClientsCache[tenantID].bucket;
39 | return;
40 | }
41 |
42 | const serviceManagerCreds = cds.env.requires?.serviceManager?.credentials;
43 | if (!serviceManagerCreds) {
44 | throw new Error("Service Manager Instance is not bound");
45 | }
46 |
47 | const { sm_url, url, clientid, clientsecret } = serviceManagerCreds;
48 | const token = await utils.fetchToken(url, clientid, clientsecret);
49 |
50 | const objectStoreCreds = await utils.getObjectStoreCredentials(tenantID, sm_url, token);
51 |
52 | if (!objectStoreCreds) {
53 | throw new Error(`SAP Object Store instance not bound for tenant ${tenantID}`);
54 | }
55 |
56 | const s3Client = new S3Client({
57 | region: objectStoreCreds.credentials.region,
58 | credentials: {
59 | accessKeyId: objectStoreCreds.credentials.access_key_id,
60 | secretAccessKey: objectStoreCreds.credentials.secret_access_key,
61 | },
62 | });
63 |
64 | s3ClientsCache[tenantID] = {
65 | client: s3Client,
66 | bucket: objectStoreCreds.credentials.bucket,
67 | };
68 |
69 | this.client = s3ClientsCache[tenantID].client;
70 | this.bucket = s3ClientsCache[tenantID].bucket;
71 | DEBUG?.(`Created S3 client for tenant ${tenantID}`);
72 | } catch (error) {
73 | // eslint-disable-next-line no-console
74 | console.error(`Creation of S3 client for tenant ${tenantID} failed`, error);
75 | }
76 | }
77 |
78 | async put(attachments, data, isDraftEnabled, _content, req) {
79 | // Check separate object store instances
80 | if (separateObjectStore) {
81 | const tenantID = req.tenant;
82 | await this.createClientS3(tenantID);
83 | }
84 |
85 | if (Array.isArray(data))
86 | return Promise.all(
87 | data.map((d) => this.put(attachments, d, isDraftEnabled))
88 | );
89 | const { content = _content, ...metadata } = data;
90 | const Key = metadata.url;
91 |
92 | const input = {
93 | Bucket: this.bucket,
94 | Key,
95 | Body: content,
96 | };
97 | try {
98 | const multipartUpload = new Upload({
99 | client: this.client,
100 | params: input,
101 | });
102 |
103 | const stored = super.put(attachments, metadata, null, isDraftEnabled);
104 | await Promise.all([stored, multipartUpload.done()]);
105 | if (this.kind === 's3') scanRequest(attachments, { ID: metadata.ID }, req)
106 | } catch (err) {
107 | console.error(err); // eslint-disable-line no-console
108 | }
109 | }
110 |
111 | // eslint-disable-next-line no-unused-vars
112 | async get(attachments, keys, req = {}) {
113 | // Check separate object store instances
114 | if (separateObjectStore) {
115 | const tenantID = req.tenant;
116 | await this.createClientS3(tenantID);
117 | }
118 | const response = await SELECT.from(attachments, keys).columns("url");
119 | if (response?.url) {
120 | const Key = response.url;
121 | const content = await this.client.send(
122 | new GetObjectCommand({
123 | Bucket: this.bucket,
124 | Key,
125 | })
126 | );
127 | return content.Body;
128 | }
129 | }
130 |
131 | async deleteAttachment(key, req) {
132 | if (!key) return;
133 | return await this.delete(key, req);
134 | }
135 |
136 | async deleteAttachmentsWithKeys(records, req) {
137 | if (req?.attachmentsToDelete?.length > 0) {
138 | req.attachmentsToDelete.forEach((attachment) => {
139 | this.deleteAttachment(attachment.url, req);
140 | });
141 | }
142 | }
143 |
144 | async attachDeletionData(req) {
145 | const attachments = cds.model.definitions[req?.target?.name + ".attachments"];
146 | if (attachments) {
147 | const diffData = await req.diff();
148 | let deletedAttachments = [];
149 | diffData.attachments?.filter((object) => {
150 | return object._op === "delete";
151 | })
152 | .map((attachment) => {
153 | deletedAttachments.push(attachment.ID);
154 | });
155 |
156 | if (deletedAttachments.length > 0) {
157 | let attachmentsToDelete = await SELECT.from(attachments).columns("url").where({ ID: { in: [...deletedAttachments] } });
158 | if (attachmentsToDelete.length > 0) {
159 | req.attachmentsToDelete = attachmentsToDelete;
160 | }
161 | }
162 | }
163 | }
164 |
165 | async updateContentHandler(req, next) {
166 | // Check separate object store instances
167 | if (separateObjectStore) {
168 | const tenantID = req.tenant;
169 | await this.createClientS3(tenantID);
170 | }
171 |
172 | if (req?.data?.content) {
173 | const response = await SELECT.from(req.target, { ID: req.data.ID }).columns("url");
174 | if (response?.url) {
175 | const Key = response.url;
176 | const input = {
177 | Bucket: this.bucket,
178 | Key,
179 | Body: req.data.content,
180 | };
181 | const multipartUpload = new Upload({
182 | client: this.client,
183 | params: input,
184 | });
185 | // const stored = super.put (Attachments, metadata)
186 | await Promise.all([multipartUpload.done()]);
187 |
188 | const keys = { ID: req.data.ID }
189 | scanRequest(req.target, keys, req)
190 | }
191 | } else if (req?.data?.note) {
192 | const key = { ID: req.data.ID };
193 | await super.update(req.target, key, { note: req.data.note });
194 | } else {
195 | next();
196 | }
197 | }
198 |
199 | async getAttachmentsToDelete({ draftEntity, activeEntity, id }) {
200 | const [draftAttachments, activeAttachments] = await Promise.all([
201 | SELECT.from(draftEntity).columns("url").where(id),
202 | SELECT.from(activeEntity).columns("url").where(id)
203 | ]);
204 |
205 | const activeUrls = new Set(activeAttachments.map(a => a.url));
206 | return draftAttachments
207 | .filter(({ url }) => !activeUrls.has(url))
208 | .map(({ url }) => ({ url }));
209 | }
210 |
211 | async attachDraftDeletionData(req) {
212 | const draftEntity = cds.model.definitions[req?.target?.name];
213 | const name = req?.target?.name;
214 | const activeEntity = name ? cds.model.definitions?.[name.split(".").slice(0, -1).join(".")] : undefined;
215 |
216 | if (!draftEntity || !activeEntity) return;
217 |
218 | const diff = await req.diff();
219 | if (diff._op !== "delete" || !diff.ID) return;
220 |
221 | const attachmentsToDelete = await this.getAttachmentsToDelete({
222 | draftEntity,
223 | activeEntity,
224 | id: { ID: diff.ID }
225 | });
226 |
227 | if (attachmentsToDelete.length) {
228 | req.attachmentsToDelete = attachmentsToDelete;
229 | }
230 | }
231 |
232 | async attachDraftDiscardDeletionData(req) {
233 | const { ID } = req.data;
234 | const parentEntity = req.target.name.split('.').slice(0, -1).join('.');
235 | const draftEntity = cds.model.definitions[`${parentEntity}.attachments.drafts`];
236 | const activeEntity = cds.model.definitions[`${parentEntity}.attachments`];
237 |
238 | if (!draftEntity || !activeEntity) return;
239 |
240 | const attachmentsToDelete = await this.getAttachmentsToDelete({
241 | draftEntity,
242 | activeEntity,
243 | id: { up__ID: ID }
244 | });
245 |
246 | if (attachmentsToDelete.length) {
247 | req.attachmentsToDelete = attachmentsToDelete;
248 | }
249 | }
250 |
251 | registerUpdateHandlers(srv, entity, mediaElement) {
252 | srv.before(["DELETE", "UPDATE"], entity, this.attachDeletionData.bind(this));
253 | srv.after(["DELETE", "UPDATE"], entity, this.deleteAttachmentsWithKeys.bind(this));
254 |
255 | // case: attachments uploaded in draft and draft is discarded
256 | srv.before("CANCEL", entity.drafts, this.attachDraftDiscardDeletionData.bind(this));
257 | srv.after("CANCEL", entity.drafts, this.deleteAttachmentsWithKeys.bind(this));
258 |
259 | srv.prepend(() => {
260 | if (mediaElement.drafts) {
261 | srv.on(
262 | "PUT",
263 | mediaElement.drafts,
264 | this.updateContentHandler.bind(this)
265 | );
266 |
267 | // case: attachments uploaded in draft and deleted before saving
268 | srv.before(
269 | "DELETE",
270 | mediaElement.drafts,
271 | this.attachDraftDeletionData.bind(this)
272 | );
273 | srv.after(
274 | "DELETE",
275 | mediaElement.drafts,
276 | this.deleteAttachmentsWithKeys.bind(this)
277 | );
278 | }
279 | });
280 | }
281 |
282 | async nonDraftHandler(attachments, data) {
283 | const isDraftEnabled = false;
284 | const response = await SELECT.from(attachments, { ID: data.ID }).columns("url");
285 | if (response?.url) data.url = response.url;
286 | return this.put(attachments, [data], isDraftEnabled);
287 | }
288 |
289 | async delete(Key, req) {
290 | // Check separate object store instances
291 | if (separateObjectStore) {
292 | const tenantID = req.tenant;
293 | await this.createClientS3(tenantID);
294 | }
295 |
296 | const response = await this.client.send(
297 | new DeleteObjectCommand({
298 | Bucket: this.bucket,
299 | Key,
300 | })
301 | );
302 | return response.DeleteMarker;
303 | }
304 |
305 | async deleteInfectedAttachment(Attachments, key, req) {
306 | const response = await SELECT.from(Attachments, key).columns('url')
307 | return await this.delete(response.url, req);
308 | }
309 | };
310 |
--------------------------------------------------------------------------------
/lib/basic.js:
--------------------------------------------------------------------------------
1 | const cds = require('@sap/cds');
2 | const DEBUG = cds.debug('attachments');
3 | const { SELECT, UPSERT, UPDATE } = cds.ql;
4 | const { scanRequest } = require('./malwareScanner')
5 |
6 | module.exports = class AttachmentsService extends cds.Service {
7 |
8 | async put(attachments, data, _content, isDraftEnabled=true) {
9 | if (!Array.isArray(data)) {
10 | if (_content) data.content = _content;
11 | data = [data];
12 | }
13 | DEBUG?.(
14 | "Uploading attachments for",
15 | attachments.name,
16 | data.map?.((d) => d.filename)
17 | );
18 |
19 | let res;
20 | if (isDraftEnabled) {
21 | res = await Promise.all(
22 | data.map(async (d) => {
23 | return await UPSERT(d).into(attachments);
24 | })
25 | );
26 | }
27 |
28 | if(this.kind === 'db') data.map((d) => { scanRequest(attachments, { ID: d.ID })})
29 |
30 | return res;
31 | }
32 |
33 | // eslint-disable-next-line no-unused-vars
34 | async get(attachments, keys, req = {}) {
35 | if (attachments.isDraft) {
36 | attachments = attachments.actives;
37 | }
38 | DEBUG?.("Downloading attachment for", attachments.name, keys);
39 | const result = await SELECT.from(attachments, keys).columns("content");
40 | return (result?.content)? result.content : null;
41 | }
42 |
43 | /**
44 | * Returns a handler to copy updated attachments content from draft to active / object store
45 | */
46 | draftSaveHandler(attachments) {
47 | const queryFields = this.getFields(attachments);
48 |
49 |
50 | return async (_, req) => {
51 | // The below query loads the attachments into streams
52 | const cqn = SELECT(queryFields)
53 | .from(attachments.drafts)
54 | .where([
55 | ...req.subject.ref[0].where.map((x) =>
56 | x.ref ? { ref: ["up_", ...x.ref] } : x
57 | )
58 | // NOTE: needs skip LargeBinary fix to Lean Draft
59 | ]);
60 | cqn.where({content: {'!=': null }})
61 | const draftAttachments = await cqn
62 |
63 | if (draftAttachments.length)
64 | await this.put(attachments, draftAttachments);
65 | };
66 | }
67 |
68 | async nonDraftHandler(attachments, data) {
69 | const isDraftEnabled = false;
70 | return this.put(attachments, [data], null, isDraftEnabled);
71 | }
72 |
73 | getFields(attachments) {
74 | const attachmentFields = ["filename", "mimeType", "content", "url", "ID"];
75 | const { up_ } = attachments.keys;
76 | if (up_)
77 | return up_.keys
78 | .map((k) => "up__" + k.ref[0])
79 | .concat(...attachmentFields)
80 | .map((k) => ({ ref: [k] }));
81 | else return Object.keys(attachments.keys);
82 | }
83 |
84 | async registerUpdateHandlers(srv, entity, target) {
85 | srv.after("SAVE", entity, this.draftSaveHandler(target));
86 | return;
87 | }
88 |
89 | async update(Attachments, key, data) {
90 | DEBUG?.("Updating attachment for", Attachments.name, key)
91 | return await UPDATE(Attachments, key).with(data)
92 | }
93 |
94 | async getStatus(Attachments, key) {
95 | const result = await SELECT.from(Attachments, key).columns('status')
96 | return result?.status;
97 | }
98 |
99 | async deleteInfectedAttachment(Attachments, key) {
100 | return await UPDATE(Attachments, key).with({ content: null})
101 | }
102 | };
103 |
--------------------------------------------------------------------------------
/lib/helper.js:
--------------------------------------------------------------------------------
1 | const axios = require('axios');
2 | const cds = require('@sap/cds');
3 | const DEBUG = cds.debug('attachments');
4 |
5 | async function fetchToken(url, clientid, clientsecret) {
6 | try {
7 | const tokenResponse = await axios.post(`${url}/oauth/token`, null, {
8 | headers: {
9 | 'Accept': 'application/json',
10 | 'Content-Type': 'application/x-www-form-urlencoded'
11 | },
12 | params: {
13 | grant_type: 'client_credentials',
14 | client_id: clientid,
15 | client_secret: clientsecret
16 | }
17 | });
18 |
19 | const token = tokenResponse.data.access_token;
20 | return token;
21 | } catch (error) {
22 | DEBUG?.(`Error fetching token: ${error.message}`);
23 | }
24 | }
25 |
26 | async function getObjectStoreCredentials(tenantID, sm_url, token) {
27 | try {
28 | const response = await axios.get(`${sm_url}/v1/service_bindings`, {
29 | params: { labelQuery: `service eq 'OBJECT_STORE' and tenant_id eq '${tenantID}'` },
30 | headers: {
31 | 'Accept': 'application/json',
32 | 'Authorization': `Bearer ${token}`,
33 | 'Content-Type': 'application/json'
34 | }
35 | });
36 |
37 | return response.data.items[0];
38 | } catch (error) {
39 | DEBUG?.(`Error fetching object store credentials: ${error.message}`);
40 | }
41 | }
42 |
43 | module.exports = {
44 | fetchToken,
45 | getObjectStoreCredentials,
46 | };
--------------------------------------------------------------------------------
/lib/malwareScanner.js:
--------------------------------------------------------------------------------
1 | const cds = require('@sap/cds')
2 | const DEBUG = cds.debug('attachments')
3 | const { SELECT } = cds.ql;
4 |
5 | async function scanRequest(Attachments, key, req) {
6 | const scanEnabled = cds.env.requires?.attachments?.scan ?? true
7 | const AttachmentsSrv = await cds.connect.to("attachments")
8 |
9 | let draftEntity, activeEntity
10 | if (Attachments.isDraft) {
11 | draftEntity = Attachments
12 | activeEntity = Attachments.actives
13 | } else {
14 | activeEntity = Attachments
15 | }
16 |
17 | let currEntity = draftEntity == undefined ? activeEntity : draftEntity
18 |
19 | if (!scanEnabled) {
20 | if (cds.env.profiles.some(p => p === "development" || p === "test") && !cds.env.profiles.includes("hybrid")) {
21 | await updateStatus(AttachmentsSrv, key, "Scanning", currEntity, draftEntity, activeEntity)
22 | setTimeout(() => {
23 | DEBUG?.('Malware scanning is disabled. Setting scan status to Clean in development profile.')
24 | updateStatus(AttachmentsSrv, key, "Clean", currEntity, draftEntity, activeEntity)
25 | .catch(e => cds.log('attachments').error(e))
26 | }, 5000).unref()
27 | return
28 | } else {
29 | return
30 | }
31 | }
32 |
33 | await updateStatus(AttachmentsSrv, key, "Scanning", currEntity, draftEntity, activeEntity)
34 |
35 | const credentials = getCredentials()
36 | const contentStream = await AttachmentsSrv.get(currEntity, key)
37 | let fileContent
38 | try {
39 | fileContent = await streamToString(contentStream)
40 | } catch (err) {
41 | DEBUG?.("Malware Scanning: Cannot read file content", err)
42 | await updateStatus(AttachmentsSrv, key, "Failed", currEntity, draftEntity, activeEntity)
43 | return
44 | }
45 |
46 | let response;
47 | try {
48 | response = await fetch(`https://${credentials.uri}/scan`, {
49 | method: "POST",
50 | headers: {
51 | Authorization:
52 | "Basic " + Buffer.from(`${credentials.username}:${credentials.password}`, "binary").toString("base64"),
53 | },
54 | body: fileContent,
55 | })
56 | } catch (error) {
57 | DEBUG?.("Request to malware scanner failed", error)
58 | await updateStatus(AttachmentsSrv, key, "Failed", currEntity, draftEntity, activeEntity)
59 | return
60 | }
61 |
62 | try {
63 | const responseText = await response.json()
64 | const status = responseText.malwareDetected ? "Infected" : "Clean"
65 | if (status === "Infected") {
66 | DEBUG?.("Malware detected in the file, deleting attachment content from db", key)
67 | await AttachmentsSrv.deleteInfectedAttachment(currEntity, key, req)
68 | }
69 | await updateStatus(AttachmentsSrv, key, status, currEntity, draftEntity, activeEntity)
70 | } catch (err) {
71 | DEBUG?.("Cannot serialize malware scanner response body", err)
72 | await updateStatus(AttachmentsSrv, key, "Failed", currEntity, draftEntity, activeEntity)
73 | }
74 | }
75 |
76 | async function updateStatus(AttachmentsSrv, key, status, currEntity, draftEntity, activeEntity) {
77 | if (currEntity == draftEntity) {
78 | currEntity = await getCurrentEntity(currEntity, activeEntity, key)
79 | }
80 | await AttachmentsSrv.update(currEntity, key, { status: status })
81 | }
82 |
83 | async function getCurrentEntity(draftEntity, activeEntity, key) {
84 | const entryInDraft = await entryExists(draftEntity, key)
85 | return entryInDraft ? draftEntity : activeEntity
86 | }
87 |
88 | async function entryExists(Attachments, key) {
89 | try {
90 | const result = await SELECT.from(Attachments, key).columns('url')
91 | return result !== null && result !== undefined
92 | } catch {
93 | return false
94 | }
95 | }
96 |
97 |
98 | function getCredentials() {
99 | try {
100 | return cds.env.requires.malwareScanner.credentials;
101 | } catch {
102 | throw new Error("SAP Malware Scanning service is not bound.");
103 | }
104 | }
105 |
106 | function streamToString(stream) {
107 | const chunks = [];
108 | return new Promise((resolve, reject) => {
109 | stream.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
110 | stream.on('error', (err) => reject(err))
111 | stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
112 | })
113 | }
114 |
115 | module.exports = {
116 | scanRequest
117 | }
118 |
--------------------------------------------------------------------------------
/lib/mtx/server.js:
--------------------------------------------------------------------------------
1 | const cds = require('@sap/cds');
2 | const axios = require('axios');
3 | const DEBUG = cds.debug('attachments');
4 | const { S3Client, paginateListObjectsV2, DeleteObjectsCommand } = require('@aws-sdk/client-s3');
5 |
6 | const PATH = {
7 | SERVICE_INSTANCE: "v1/service_instances",
8 | SERVICE_BINDING: "v1/service_bindings",
9 | SERVICE_PLAN: "v1/service_plans",
10 | SERVICE_OFFERING: "v1/service_offerings"
11 | };
12 |
13 | const HTTP_METHOD = {
14 | POST: "post",
15 | GET: "get",
16 | DELETE: "delete"
17 | };
18 |
19 | const STATE = {
20 | SUCCEEDED: "succeeded",
21 | FAILED: "failed",
22 | };
23 |
24 | let POLL_WAIT_TIME = 5000;
25 | const ASYNC_TIMEOUT = 5 * 60 * 1000;
26 |
27 | async function wait(milliseconds) {
28 | if (milliseconds <= 0) {
29 | return;
30 | }
31 | await new Promise(function (resolve) {
32 | setTimeout(resolve, milliseconds);
33 | });
34 | }
35 |
36 | const _serviceManagerRequest = async (sm_url, method, path, token, params = {}) => {
37 | try {
38 | const response = await axios({
39 | method,
40 | url: `${sm_url}/${path}`,
41 | headers: {
42 | 'Accept': 'application/json',
43 | 'Authorization': `Bearer ${token}`
44 | },
45 | params
46 | });
47 |
48 | return response.data.items[0];
49 |
50 | } catch (error) {
51 | DEBUG?.(`Error fetching data from service manager: ${error.message}`);
52 | }
53 | };
54 |
55 | const _fetchToken = async (url, clientid, clientsecret) => {
56 | try {
57 | const tokenResponse = await axios.post(`${url}/oauth/token`, null, {
58 | headers: {
59 | 'Accept': 'application/json',
60 | 'Content-Type': 'application/x-www-form-urlencoded'
61 | },
62 | params: {
63 | grant_type: 'client_credentials',
64 | client_id: clientid,
65 | client_secret: clientsecret
66 | }
67 | });
68 |
69 | return tokenResponse.data.access_token;
70 | } catch (error) {
71 | DEBUG?.(`Error fetching token from service manager: ${error.message}`);
72 | }
73 | };
74 |
75 | const _getOfferingID = async (sm_url, token) => {
76 | const offerings = await _serviceManagerRequest(sm_url, HTTP_METHOD.GET, PATH.SERVICE_OFFERING, token, { fieldQuery: "name eq 'objectstore'" });
77 | const offeringID = offerings.id;
78 | if (!offeringID) DEBUG?.('Object store service offering not found');
79 | return offeringID;
80 | }
81 |
82 | const _getPlanID = async (sm_url, token, offeringID) => {
83 | // Recheck the fieldQuery for catalog_name
84 | const plans = await _serviceManagerRequest(sm_url, HTTP_METHOD.GET, PATH.SERVICE_PLAN, token, { fieldQuery: `service_offering_id eq '${offeringID}' and catalog_name eq 's3-standard'` });
85 | const planID = plans.id;
86 | if (!planID) DEBUG?.('Object store service plan not found');
87 | return planID;
88 | };
89 |
90 | const _createObjectStoreInstance = async (sm_url, tenant, planID, token) => {
91 | try {
92 | const response = await axios.post(`${sm_url}/v1/service_instances`, {
93 | name: `object-store-${tenant}-${cds.utils.uuid()}`,
94 | service_plan_id: planID,
95 | parameters: {},
96 | labels: { tenant_id: [tenant], service: ["OBJECT_STORE"] }
97 | }, {
98 | headers: {
99 | 'Accept': 'application/json',
100 | 'Authorization': `Bearer ${token}`,
101 | 'Content-Type': 'application/json'
102 | }
103 | });
104 | const instancePath = response.headers.location.substring(1);
105 | const instanceId = await _pollUntilDone(sm_url, instancePath, token);
106 | return instanceId.data.resource_id;
107 | } catch (error) {
108 | DEBUG?.(`Error creating object store instance - ${tenant}: ${error.message}`);
109 | }
110 | };
111 |
112 | const _pollUntilDone = async (sm_url, instancePath, token) => {
113 | try {
114 | let iteration = 1;
115 | const startTime = Date.now();
116 | let isReady = false;
117 | while (!isReady) {
118 | await wait(POLL_WAIT_TIME * iteration);
119 | iteration++;
120 |
121 | const instanceStatus = await axios.get(`${sm_url}/${instancePath}`, {
122 | headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${token}` }
123 | });
124 |
125 | if (instanceStatus.data.state === STATE.SUCCEEDED) {
126 | isReady = true;
127 | return instanceStatus;
128 | }
129 |
130 | if (Date.now() - startTime > ASYNC_TIMEOUT) {
131 | DEBUG?.('Timed out waiting for service instance to be ready');
132 | }
133 |
134 | if (instanceStatus.data.state === STATE.FAILED) {
135 | DEBUG?.('Service instance creation failed');
136 | }
137 | }
138 | } catch (error) {
139 | DEBUG?.(`Error polling for object store instance readiness: ${error.message}`);
140 | }
141 | };
142 |
143 | const _bindObjectStoreInstance = async (sm_url, tenant, instanceID, token) => {
144 | if (instanceID) {
145 | try {
146 | const response = await axios.post(`${sm_url}/${PATH.SERVICE_BINDING}`, {
147 | name: `object-store-${tenant}-${cds.utils.uuid()}`,
148 | service_instance_id: instanceID,
149 | parameters: {},
150 | labels: { tenant_id: [tenant], service: ["OBJECT_STORE"] }
151 | }, {
152 | headers: {
153 | 'Accept': 'application/json',
154 | 'Authorization': `Bearer ${token}`,
155 | 'Content-Type': 'application/json'
156 | }
157 | });
158 | return response.data.id;
159 | } catch (error) {
160 | DEBUG?.(`Error binding object store instance for tenant - ${tenant}: ${error.message}`);
161 | }
162 | }
163 | };
164 |
165 | const _getBindingIdForDeletion = async (sm_url, tenant, token) => {
166 | try {
167 | const getBindingCredentials = await _serviceManagerRequest(sm_url, HTTP_METHOD.GET, PATH.SERVICE_BINDING, token, {
168 | labelQuery: `service eq 'OBJECT_STORE' and tenant_id eq '${tenant}'`
169 | });
170 | if (!getBindingCredentials?.id) {
171 | DEBUG?.("No binding credentials found!");
172 | return null; // Handle missing data gracefully
173 | }
174 | return getBindingCredentials.id;
175 |
176 | } catch (error) {
177 | DEBUG?.(`Error fetching binding credentials for tenant - ${tenant}: ${error.message}`);
178 | }
179 | };
180 |
181 | const _deleteBinding = async (sm_url, bindingID, token) => {
182 | if (bindingID) {
183 | try {
184 | await axios.delete(`${sm_url}/${PATH.SERVICE_BINDING}/${bindingID}`, {
185 | headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${token}` }
186 | });
187 | } catch (error) {
188 | DEBUG?.('Error deleting binding:', error.message);
189 | }
190 | } else {
191 | DEBUG?.("Binding id is either undefined or null");
192 | }
193 | };
194 |
195 | const _getInstanceIdForDeletion = async (sm_url, tenant, token) => {
196 | try {
197 | const instanceId = await _serviceManagerRequest(sm_url, HTTP_METHOD.GET, PATH.SERVICE_INSTANCE, token, { labelQuery: `service eq 'OBJECT_STORE' and tenant_id eq '${tenant}'` });
198 | return instanceId.id;
199 | } catch (error) {
200 | DEBUG?.(`Error fetching service instance id for tenant - ${tenant}: ${error.message}`);
201 | }
202 | }
203 |
204 | const _deleteObjectStoreInstance = async (sm_url, instanceID, token) => {
205 | if (instanceID) {
206 | try {
207 | const response = await axios.delete(`${sm_url}/${PATH.SERVICE_INSTANCE}/${instanceID}`, {
208 | headers: { 'Accept': 'application/json', 'Authorization': `Bearer ${token}` }
209 | });
210 | const instancePath = response.headers.get("location").substring(1);
211 | await _pollUntilDone(sm_url, instancePath, token); // remove
212 | DEBUG?.('Object Store instance deleted');
213 | } catch (error) {
214 | DEBUG?.(`Error deleting object store instance - ${instanceID}: ${error.message}`);
215 | }
216 | }
217 | };
218 |
219 | cds.on('listening', async () => {
220 | const profile = cds.env.profile;
221 | const objectStoreKind = cds.env.requires?.attachments?.objectStore?.kind;
222 | if (profile === 'mtx-sidecar') {
223 | const ds = await cds.connect.to("cds.xt.DeploymentService");
224 | if (objectStoreKind === "separate") {
225 | ds.after('subscribe', async (_, req) => {
226 | const { tenant } = req.data;
227 | try {
228 | const serviceManagerCredentials = cds.env.requires?.serviceManager?.credentials;
229 | const { sm_url, url, clientid, clientsecret } = serviceManagerCredentials;
230 |
231 | const token = await _fetchToken(url, clientid, clientsecret)
232 |
233 | const offeringID = await _getOfferingID(sm_url, token);
234 |
235 | const planID = await _getPlanID(sm_url, token, offeringID);
236 |
237 | const instanceID = await _createObjectStoreInstance(sm_url, tenant, planID, token);
238 | DEBUG?.('Object Store instance created');
239 |
240 | await _bindObjectStoreInstance(sm_url, tenant, instanceID, token);
241 | } catch (error) {
242 | // eslint-disable-next-line no-console
243 | console.error(`Error setting up object store for tenant - ${tenant}: ${error.message}`);
244 | }
245 | });
246 |
247 | ds.after('unsubscribe', async (_, req) => {
248 | const { tenant } = req.data;
249 | try {
250 | const serviceManagerCredentials = cds.env.requires?.serviceManager?.credentials;
251 | const { sm_url, url, clientid, clientsecret } = serviceManagerCredentials;
252 |
253 | const token = await _fetchToken(url, clientid, clientsecret)
254 |
255 | const bindingID = await _getBindingIdForDeletion(sm_url, tenant, token);
256 |
257 | await _deleteBinding(sm_url, bindingID, token);
258 |
259 | const service_instance_id = await _getInstanceIdForDeletion(sm_url, tenant, token);
260 |
261 | await _deleteObjectStoreInstance(sm_url, service_instance_id, token);
262 | } catch (error) {
263 | // eslint-disable-next-line no-console
264 | console.error(`Error deleting object store service for tenant - ${tenant}: ${error.message}`);
265 | }
266 |
267 | });
268 | } else if (objectStoreKind === "shared") {
269 | ds.after('unsubscribe', async (_, req) => {
270 | const { tenant } = req.data;
271 |
272 | const creds = cds.env.requires?.objectStore?.credentials;
273 | if (!creds) throw new Error("SAP Object Store instance credentials not found.");
274 |
275 | const client = new S3Client({
276 | region: creds.region,
277 | credentials: {
278 | accessKeyId: creds.access_key_id,
279 | secretAccessKey: creds.secret_access_key,
280 | },
281 | });
282 |
283 | const bucket = creds.bucket;
284 | const keysToDelete = [];
285 |
286 | try {
287 | const paginator = paginateListObjectsV2({ client }, {
288 | Bucket: bucket,
289 | Prefix: tenant,
290 | });
291 |
292 | for await (const page of paginator) {
293 | page.Contents?.forEach(obj => {
294 | keysToDelete.push({ Key: obj.Key });
295 | });
296 | }
297 |
298 | if (keysToDelete.length > 0) {
299 | await client.send(new DeleteObjectsCommand({
300 | Bucket: bucket,
301 | Delete: { Objects: keysToDelete },
302 | }));
303 | console.debug(`S3 objects deleted for tenant: ${tenant}`);
304 | } else {
305 | console.debug(`No S3 objects found for tenant: ${tenant}`);
306 | }
307 | } catch (error) {
308 | console.error(`Failed to clean up S3 objects for tenant "${tenant}": ${error.message}`);
309 | }
310 | });
311 |
312 | }
313 | }
314 | module.exports = cds.server;
315 | });
316 |
--------------------------------------------------------------------------------
/lib/plugin.js:
--------------------------------------------------------------------------------
1 | const cds = require("@sap/cds/lib")
2 | const LOG = cds.log("attachments")
3 | const { extname } = require("path")
4 | const DEBUG = LOG._debug ? LOG.debug : undefined
5 | const attachmentIDRegex = /\/\w+\(.*ID=([0-9a-fA-F-]{36})/
6 |
7 | cds.on(cds.version >= "8.6.0" ? "compile.to.edmx" : "loaded", unfoldModel);
8 | function unfoldModel (csn) {
9 | const meta = csn.meta ??= {}
10 | if (!("sap.attachments.Attachments" in csn.definitions)) return
11 | if (meta._enhanced_for_attachments) return
12 | // const csnCopy = structuredClone(csn) // REVISIT: Why did we add this cloning?
13 | cds.linked(csn).forall("Composition", (comp) => {
14 | if (comp._target && comp._target["@_is_media_data"] && comp.parent && comp.is2many) {
15 | let facets = comp.parent["@UI.Facets"]
16 | if (!facets) return
17 | DEBUG?.("Adding @UI.Facet to:", comp.parent.name)
18 | if(!comp["@attachments.disable_facet"]){
19 | facets.push({
20 | $Type: "UI.ReferenceFacet",
21 | Target: `${comp.name}/@UI.LineItem`,
22 | Label: "{i18n>Attachments}",
23 | })
24 | }
25 |
26 | }
27 | })
28 | meta._enhanced_for_attachments = true
29 | }
30 |
31 | cds.once("served", async function registerPluginHandlers () {
32 | if (!("sap.attachments.Attachments" in cds.model.definitions)) return
33 | const AttachmentsSrv = await cds.connect.to("attachments")
34 | // Searching all associations to attachments to add respective handlers
35 | for (let srv of cds.services) {
36 | if (srv instanceof cds.ApplicationService) {
37 | Object.values(srv.entities).forEach((entity) => {
38 |
39 | for (let elementName in entity.elements) {
40 | if (elementName === "SiblingEntity") continue // REVISIT: Why do we have this?
41 | const element = entity.elements[elementName], target = element._target
42 |
43 | if (!target?.["@_is_media_data"]) continue;
44 |
45 | const isDraft = !!target?.drafts;
46 | const targets = isDraft ? [target, target.drafts] : [target];
47 |
48 | DEBUG?.("serving attachments for:", target.name)
49 |
50 | srv.before("READ", targets, validateAttachment)
51 |
52 | srv.after("READ", targets, readAttachment)
53 |
54 | const putTarget = isDraft ? target.drafts : target;
55 | srv.before("PUT", putTarget, (req) => validateAttachmentSize(req))
56 |
57 | const op = isDraft ? "NEW" : "CREATE";
58 | srv.before(op, putTarget, (req) => {
59 | req.data.url = cds.utils.uuid()
60 | const isMultitenacyEnabled = !!cds.env.requires.multitenancy;
61 | const objectStoreKind = cds.env.requires?.attachments?.objectStore?.kind;
62 | if (isMultitenacyEnabled && objectStoreKind === "shared") {
63 | req.data.url = `${req.tenant}_${req.data.url}`;
64 | }
65 | req.data.ID = cds.utils.uuid()
66 | let ext = extname(req.data.filename).toLowerCase().slice(1)
67 | req.data.mimeType = Ext2MimeTyes[ext] || "application/octet-stream"
68 | });
69 |
70 | if (isDraft) {
71 | AttachmentsSrv.registerUpdateHandlers(srv, entity, target)
72 | } else {
73 | srv.after("PUT", target, (req) => nonDraftUpload(req, target))
74 | }
75 | }
76 | })
77 | }
78 | }
79 |
80 | async function validateAttachment (req) {
81 |
82 | /* removing case condition for mediaType annotation as in our case binary value and metadata is stored in different database */
83 |
84 | req?.query?.SELECT?.columns?.forEach((element) => {
85 | if (element.as === 'content@odata.mediaContentType' && element.xpr) {
86 | delete element.xpr
87 | element.ref = ['mimeType']
88 | }
89 | })
90 |
91 | if (req?.req?.url?.endsWith("/content")) {
92 | const attachmentID = req.req.url.match(attachmentIDRegex)[1]
93 | const status = await AttachmentsSrv.getStatus(req.target, { ID: attachmentID })
94 | const scanEnabled = cds.env.requires?.attachments?.scan ?? true
95 | if (scanEnabled && status !== 'Clean') {
96 | req.reject(403, 'Unable to download the attachment as scan status is not clean.')
97 | }
98 | }
99 | }
100 |
101 | async function readAttachment ([attachment], req) {
102 | if (!req?.req?.url?.endsWith("/content") || !attachment || attachment?.content) return
103 | let keys = { ID: req.req.url.match(attachmentIDRegex)[1] }
104 | let { target } = req
105 | attachment.content = await AttachmentsSrv.get(target, keys, req) //Dependency -> sending req object for usage in SDM plugin
106 | }
107 |
108 | async function nonDraftUpload(req, target) {
109 | if (req?.content?.url?.endsWith("/content")) {
110 | const attachmentID = req.content.url.match(attachmentIDRegex)[1];
111 | AttachmentsSrv.nonDraftHandler(target, { ID: attachmentID, content: req.content });
112 | }
113 | }
114 | })
115 |
116 | function validateAttachmentSize (req) {
117 | const contentLengthHeader = req.headers["content-length"]
118 | let fileSizeInBytes
119 |
120 | if (contentLengthHeader) {
121 | fileSizeInBytes = Number(contentLengthHeader)
122 | const MAX_FILE_SIZE = 419430400 //400 MB in bytes
123 | if (fileSizeInBytes > MAX_FILE_SIZE) {
124 | return req.reject(403, "File Size limit exceeded beyond 400 MB.")
125 | }
126 | } else {
127 | return req.reject(403, "Invalid Content Size")
128 | }
129 | }
130 |
131 | module.exports = { validateAttachmentSize }
132 |
133 | const Ext2MimeTyes = {
134 | aac: "audio/aac",
135 | abw: "application/x-abiword",
136 | arc: "application/octet-stream",
137 | avi: "video/x-msvideo",
138 | azw: "application/vnd.amazon.ebook",
139 | bin: "application/octet-stream",
140 | png: "image/png",
141 | gif: "image/gif",
142 | bmp: "image/bmp",
143 | bz: "application/x-bzip",
144 | bz2: "application/x-bzip2",
145 | csh: "application/x-csh",
146 | css: "text/css",
147 | csv: "text/csv",
148 | doc: "application/msword",
149 | docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
150 | odp: "application/vnd.oasis.opendocument.presentation",
151 | ods: "application/vnd.oasis.opendocument.spreadsheet",
152 | odt: "application/vnd.oasis.opendocument.text",
153 | epub: "application/epub+zip",
154 | gz: "application/gzip",
155 | htm: "text/html",
156 | html: "text/html",
157 | ico: "image/x-icon",
158 | ics: "text/calendar",
159 | jar: "application/java-archive",
160 | jpg: "image/jpeg",
161 | jpeg: "image/jpeg",
162 | js: "text/javascript",
163 | json: "application/json",
164 | mid: "audio/midi",
165 | midi: "audio/midi",
166 | mjs: "text/javascript",
167 | mov: "video/quicktime",
168 | mp3: "audio/mpeg",
169 | mp4: "video/mp4",
170 | mpeg: "video/mpeg",
171 | mpkg: "application/vnd.apple.installer+xml",
172 | otf: "font/otf",
173 | pdf: "application/pdf",
174 | ppt: "application/vnd.ms-powerpoint",
175 | pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
176 | rar: "application/x-rar-compressed",
177 | rtf: "application/rtf",
178 | svg: "image/svg+xml",
179 | tar: "application/x-tar",
180 | tif: "image/tiff",
181 | tiff: "image/tiff",
182 | ttf: "font/ttf",
183 | vsd: "application/vnd.visio",
184 | wav: "audio/wav",
185 | woff: "font/woff",
186 | woff2: "font/woff2",
187 | xhtml: "application/xhtml+xml",
188 | xls: "application/vnd.ms-excel",
189 | xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
190 | xml: "application/xml",
191 | zip: "application/zip",
192 | txt: "application/txt",
193 | lst: "application/txt"
194 | }
195 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@cap-js/attachments",
3 | "description": "CAP cds-plugin providing image and attachment storing out-of-the-box.",
4 | "version": "2.1.2",
5 | "repository": "cap-js/attachments",
6 | "author": "SAP SE (https://www.sap.com)",
7 | "homepage": "https://cap.cloud.sap/",
8 | "license": "Apache-2.0",
9 | "main": "cds-plugin.js",
10 | "files": [
11 | "index.cds",
12 | "lib",
13 | "srv"
14 | ],
15 | "scripts": {
16 | "lint": "npx eslint .",
17 | "test": "npx jest --runInBand"
18 | },
19 | "dependencies": {
20 | "@aws-sdk/client-s3": "^3.400.0",
21 | "@aws-sdk/lib-storage": "^3.515.0",
22 | "axios": "^1.4.0"
23 | },
24 | "devDependencies": {
25 | "@cap-js/cds-test": ">=0",
26 | "@cap-js/sqlite": "^2",
27 | "express": "^4.18.2"
28 | },
29 | "peerDependencies": {
30 | "@sap/cds": ">=8"
31 | },
32 | "engines": {
33 | "node": ">=17.0.0"
34 | },
35 | "cds": {
36 | "requires": {
37 | "malwareScanner": {
38 | "vcap": {
39 | "label": "malware-scanner"
40 | }
41 | },
42 | "kinds": {
43 | "attachments-db": {
44 | "impl": "@cap-js/attachments/lib/basic"
45 | },
46 | "attachments-s3": {
47 | "impl": "@cap-js/attachments/lib/aws-s3"
48 | }
49 | },
50 | "serviceManager":{
51 | "vcap": {
52 | "label": "service-manager"
53 | }
54 | },
55 | "objectStore":{
56 | "vcap": {
57 | "label": "objectstore"
58 | }
59 | },
60 | "attachments": {
61 | "scan": true,
62 | "objectStore": {
63 | "kind": "separate"
64 | }
65 | },
66 | "[development]": {
67 | "attachments": {
68 | "scan": false,
69 | "kind": "db"
70 | }
71 | },
72 | "[production]": {
73 | "attachments": {
74 | "kind": "s3",
75 | "objectStore": {
76 | "kind": "separate"
77 | }
78 | }
79 | },
80 | "[hybrid]": {
81 | "attachments": {
82 | "kind": "s3",
83 | "scan": true,
84 | "objectStore": {
85 | "kind": "separate"
86 | }
87 | }
88 | }
89 | }
90 | }
91 | }
92 |
--------------------------------------------------------------------------------
/tests/incidents-app/app/incidents/annotations.cds:
--------------------------------------------------------------------------------
1 | using ProcessorService as service from '../../srv/services';
2 | using from '../../db/schema';
3 |
4 | annotate service.Customers with @title : '{i18n>Customer}';
5 | annotate service.Incidents with @title : '{i18n>Incident}';
6 | annotate service.Incidents with @odata.draft.enabled;
7 |
8 | annotate service.Incidents with @(
9 | UI.LineItem : [
10 | {
11 | $Type : 'UI.DataField',
12 | Value : title,
13 | Label : '{i18n>Title}',
14 | },
15 | {
16 | $Type : 'UI.DataField',
17 | Value : customer.name,
18 | Label : '{i18n>Customer}',
19 | },
20 | {
21 | $Type : 'UI.DataField',
22 | Value : status.descr,
23 | Criticality : status.criticality,
24 | Label : '{i18n>Status}',
25 | },
26 | {
27 | $Type : 'UI.DataField',
28 | Value : urgency.descr,
29 | Label : '{i18n>Urgency}',
30 | },
31 | ]
32 | );
33 | annotate service.Incidents with @(
34 | UI.FieldGroup #GeneratedGroup1 : {
35 | $Type : 'UI.FieldGroupType',
36 | Data : [
37 | {
38 | $Type : 'UI.DataField',
39 | Value : title,
40 | Label : '{i18n>Title}',
41 | },
42 | {
43 | $Type : 'UI.DataField',
44 | Value : customer_ID,
45 | Label : '{i18n>Customer}',
46 | },
47 | ],
48 | },
49 | UI.Facets : [
50 | {
51 | $Type : 'UI.CollectionFacet',
52 | Label : '{i18n>Overview}',
53 | ID : 'i18nOverview',
54 | Facets : [
55 | {
56 | $Type : 'UI.ReferenceFacet',
57 | ID : 'GeneratedFacet1',
58 | Label : 'General Information',
59 | Target : '@UI.FieldGroup#GeneratedGroup1',
60 | },
61 | {
62 | $Type : 'UI.ReferenceFacet',
63 | Label : '{i18n>Details}',
64 | ID : 'i18nDetails',
65 | Target : '@UI.FieldGroup#i18nDetails',
66 | },],
67 | },
68 | {
69 | $Type : 'UI.ReferenceFacet',
70 | Label : '{i18n>Conversation}',
71 | ID : 'i18nConversation',
72 | Target : 'conversation/@UI.LineItem#i18nConversation1',
73 | },
74 | ]
75 | );
76 | annotate service.Incidents with @(
77 | UI.SelectionFields : [
78 | urgency_code,
79 | status_code,
80 | ]
81 | );
82 | annotate service.Incidents with {
83 | status @Common.Label : '{i18n>Status}'
84 | };
85 | annotate service.Incidents with {
86 | urgency @Common.Label : '{i18n>Urgency}'
87 | };
88 | annotate service.Incidents with {
89 | status @Common.ValueListWithFixedValues : true
90 | };
91 | annotate service.Incidents with {
92 | urgency @Common.ValueListWithFixedValues : true
93 | };
94 | annotate service.Incidents with @(
95 | UI.HeaderInfo : {
96 | Title : {
97 | $Type : 'UI.DataField',
98 | Value : title,
99 | },
100 | TypeName : '',
101 | TypeNamePlural : '',
102 | Description : {
103 | $Type : 'UI.DataField',
104 | Value : customer.name,
105 | },
106 | TypeImageUrl : 'sap-icon://alert',
107 | }
108 | );
109 | annotate service.Incidents with @(
110 | UI.FieldGroup #i18nDetails : {
111 | $Type : 'UI.FieldGroupType',
112 | Data : [
113 | {
114 | $Type : 'UI.DataField',
115 | Value : status_code,
116 | Criticality : status.criticality,
117 | },
118 | {
119 | $Type : 'UI.DataField',
120 | Value : urgency_code,
121 | },],
122 | }
123 | );
124 | annotate service.Status with {
125 | code @Common.Text : descr
126 | };
127 | annotate service.Urgency with {
128 | code @Common.Text : descr
129 | };
130 | annotate service.Incidents with {
131 | customer @(Common.ValueList : {
132 | $Type : 'Common.ValueListType',
133 | CollectionPath : 'Customers',
134 | Parameters : [
135 | {
136 | $Type : 'Common.ValueListParameterInOut',
137 | LocalDataProperty : customer_ID,
138 | ValueListProperty : 'ID',
139 | },
140 | {
141 | $Type : 'Common.ValueListParameterDisplayOnly',
142 | ValueListProperty : 'name',
143 | },
144 | {
145 | $Type : 'Common.ValueListParameterDisplayOnly',
146 | ValueListProperty : 'email',
147 | },
148 | ],
149 | },
150 | Common.ValueListWithFixedValues : false
151 | )};
152 |
153 | annotate service.Incidents with {
154 | status @Common.Text : status.descr
155 | };
156 | annotate service.Incidents with {
157 | urgency @Common.Text : urgency.descr
158 | };
159 | annotate service.Incidents with {
160 | customer @Common.Text : {
161 | $value : customer.name,
162 | ![@UI.TextArrangement] : #TextOnly,
163 | }
164 | };
165 | annotate service.Incidents.conversation with @(
166 | title : '{i18n>Conversation}',
167 | UI.LineItem #i18nConversation1 : [
168 | {
169 | $Type : 'UI.DataField',
170 | Value : author,
171 | Label : '{i18n>Author}',
172 | },
173 | {
174 | $Type : 'UI.DataField',
175 | Value : timestamp,
176 | Label : '{i18n>ConversationDate}',
177 | },{
178 | $Type : 'UI.DataField',
179 | Value : message,
180 | Label : '{i18n>Message}',
181 | },]
182 | );
183 |
--------------------------------------------------------------------------------
/tests/incidents-app/app/incidents/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "incidents",
3 | "version": "0.0.1",
4 | "description": "A Fiori application.",
5 | "keywords": [
6 | "ui5",
7 | "openui5",
8 | "sapui5"
9 | ],
10 | "main": "webapp/index.html",
11 | "scripts": {
12 | "deploy-config": "npx -p @sap/ux-ui5-tooling fiori add deploy-config cf"
13 | },
14 | "devDependencies": { }
15 | }
16 |
--------------------------------------------------------------------------------
/tests/incidents-app/app/incidents/ui5.yaml:
--------------------------------------------------------------------------------
1 | specVersion: "2.5"
2 | metadata:
3 | name: ns.incidents
4 | type: application
5 |
--------------------------------------------------------------------------------
/tests/incidents-app/app/incidents/webapp/i18n/i18n.properties:
--------------------------------------------------------------------------------
1 | # This is the resource bundle for ns.incidents
2 |
3 | #Texts for manifest.json
4 |
5 | #XTIT: Application name
6 | appTitle=Incident-Management
7 |
8 | #YDES: Application description
9 | appDescription=A Fiori application.
--------------------------------------------------------------------------------
/tests/incidents-app/app/incidents/webapp/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 | Incident-Management
8 |
13 |
25 |
26 |
27 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/tests/incidents-app/app/incidents/webapp/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "_version": "1.49.0",
3 | "sap.app": {
4 | "id": "ns.incidents",
5 | "type": "application",
6 | "i18n": "i18n/i18n.properties",
7 | "applicationVersion": {
8 | "version": "0.0.1"
9 | },
10 | "title": "{{appTitle}}",
11 | "description": "{{appDescription}}",
12 | "resources": "resources.json",
13 | "sourceTemplate": {
14 | "id": "@sap/generator-fiori:lrop",
15 | "version": "1.9.7",
16 | "toolsId": "b6e2272d-1167-41a4-baed-217444579193"
17 | },
18 | "crossNavigation": {
19 | "inbounds": {
20 | "intent1": {
21 | "signature": {
22 | "parameters": {},
23 | "additionalParameters": "allowed"
24 | },
25 | "semanticObject": "Incidents",
26 | "action": "display"
27 | }
28 | }
29 | },
30 | "dataSources": {
31 | "mainService": {
32 | "uri": "/odata/v4/processor/",
33 | "type": "OData",
34 | "settings": {
35 | "annotations": [],
36 | "localUri": "localService/metadata.xml",
37 | "odataVersion": "4.0"
38 | }
39 | }
40 | }
41 | },
42 | "sap.ui": {
43 | "technology": "UI5",
44 | "icons": {
45 | "icon": "",
46 | "favIcon": "",
47 | "phone": "",
48 | "phone@2": "",
49 | "tablet": "",
50 | "tablet@2": ""
51 | },
52 | "deviceTypes": {
53 | "desktop": true,
54 | "tablet": true,
55 | "phone": true
56 | }
57 | },
58 | "sap.ui5": {
59 | "flexEnabled": true,
60 | "dependencies": {
61 | "minUI5Version": "1.120.0",
62 | "libs": {
63 | "sap.m": {},
64 | "sap.ui.core": {},
65 | "sap.ushell": {},
66 | "sap.fe.templates": {}
67 | }
68 | },
69 | "contentDensities": {
70 | "compact": true,
71 | "cozy": true
72 | },
73 | "models": {
74 | "i18n": {
75 | "type": "sap.ui.model.resource.ResourceModel",
76 | "settings": {
77 | "bundleName": "ns.incidents.i18n.i18n"
78 | }
79 | },
80 | "": {
81 | "dataSource": "mainService",
82 | "preload": true,
83 | "settings": {
84 | "synchronizationMode": "None",
85 | "operationMode": "Server",
86 | "autoExpandSelect": true,
87 | "earlyRequests": true
88 | }
89 | },
90 | "@i18n": {
91 | "type": "sap.ui.model.resource.ResourceModel",
92 | "uri": "i18n/i18n.properties"
93 | }
94 | },
95 | "resources": {
96 | "css": []
97 | },
98 | "routing": {
99 | "routes": [
100 | {
101 | "pattern": ":?query:",
102 | "name": "IncidentsList",
103 | "target": "IncidentsList"
104 | },
105 | {
106 | "pattern": "Incidents({key}):?query:",
107 | "name": "IncidentsObjectPage",
108 | "target": "IncidentsObjectPage"
109 | }
110 | ],
111 | "targets": {
112 | "IncidentsList": {
113 | "type": "Component",
114 | "id": "IncidentsList",
115 | "name": "sap.fe.templates.ListReport",
116 | "options": {
117 | "settings": {
118 | "entitySet": "Incidents",
119 | "variantManagement": "Page",
120 | "navigation": {
121 | "Incidents": {
122 | "detail": {
123 | "route": "IncidentsObjectPage"
124 | }
125 | }
126 | },
127 | "initialLoad": "Enabled",
128 | "controlConfiguration": {
129 | "@com.sap.vocabularies.UI.v1.LineItem": {
130 | "tableSettings": {
131 | "type": "ResponsiveTable"
132 | }
133 | }
134 | }
135 | }
136 | }
137 | },
138 | "IncidentsObjectPage": {
139 | "type": "Component",
140 | "id": "IncidentsObjectPage",
141 | "name": "sap.fe.templates.ObjectPage",
142 | "options": {
143 | "settings": {
144 | "editableHeaderContent": false,
145 | "entitySet": "Incidents",
146 | "navigation": {},
147 | "controlConfiguration": {
148 | "conversations/@com.sap.vocabularies.UI.v1.LineItem#i18nConversations": {
149 | "tableSettings": {
150 | "type": "ResponsiveTable",
151 | "creationMode": {
152 | "name": "Inline"
153 | }
154 | }
155 | }
156 | }
157 | }
158 | }
159 | }
160 | }
161 | },
162 | "extends": {
163 | "extensions": {
164 | "sap.ui.controllerExtensions": {}
165 | }
166 | }
167 | },
168 | "sap.fiori": {
169 | "registrationIds": [],
170 | "archeType": "transactional"
171 | }
172 | }
--------------------------------------------------------------------------------
/tests/incidents-app/app/incidents/webapp/xs-app.json:
--------------------------------------------------------------------------------
1 | {
2 | "authenticationMethod": "route",
3 | "logout": {
4 | "logoutEndpoint": "/do/logout"
5 | },
6 | "routes": [
7 | {
8 | "source": "^(.*)$",
9 | "target": "$1",
10 | "service": "html5-apps-repo-rt",
11 | "authenticationType": "xsuaa"
12 | }
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/tests/incidents-app/app/services.cds:
--------------------------------------------------------------------------------
1 |
2 | using from './incidents/annotations';
--------------------------------------------------------------------------------
/tests/incidents-app/db/attachments.cds:
--------------------------------------------------------------------------------
1 |
2 | using { sap.capire.incidents as my } from './schema';
3 | using { Attachments } from '@cap-js/attachments';
4 |
5 | extend my.Incidents with {
6 | attachments: Composition of many Attachments;
7 | @attachments.disable_facet
8 | hiddenAttachments: Composition of many Attachments;
9 | }
--------------------------------------------------------------------------------
/tests/incidents-app/db/data/sap.capire.incidents-Addresses.csv:
--------------------------------------------------------------------------------
1 | ID,customer_ID,city,postCode,streetAddress
2 | 17e00347-dc7e-4ca9-9c5d-06ccef69f064,1004155,Rome,00164,Piazza Adriana
3 | d8e797d9-6507-4aaa-b43f-5d2301df5135,1004161,Munich,80809,Olympia Park
4 | ff13d2fa-e00f-4ee5-951c-3303f490777b,1004100,Walldorf,69190,Dietmar-Hopp-Allee
5 |
--------------------------------------------------------------------------------
/tests/incidents-app/db/data/sap.capire.incidents-Customers.csv:
--------------------------------------------------------------------------------
1 | ID,firstName,lastName,email,phone
2 | 1004155,Daniel,Watts,daniel.watts@demo.com,+44-555-123
3 | 1004161,Stormy,Weathers,stormy.weathers@demo.com,
4 | 1004100,Sunny,Sunshine,sunny.sunshine@demo.com,+01-555-789
5 |
--------------------------------------------------------------------------------
/tests/incidents-app/db/data/sap.capire.incidents-Incidents.conversation.csv:
--------------------------------------------------------------------------------
1 | ID,up__ID,timestamp,author,message
2 | 2b23bb4b-4ac7-4a24-ac02-aa10cabd842c,3b23bb4b-4ac7-4a24-ac02-aa10cabd842c,1995-12-17T03:24:00Z,Harry John,Can you please check if battery connections are fine?
3 | 2b23bb4b-4ac7-4a24-ac02-aa10cabd843c,3a4ede72-244a-4f5f-8efa-b17e032d01ee,1995-12-18T04:24:00Z,Emily Elizabeth,Can you please check if there are any loose connections?
4 | 9583f982-d7df-4aad-ab26-301d4a157cd7,3583f982-d7df-4aad-ab26-301d4a157cd7,2022-09-04T12:00:00Z,Sunny Sunshine,Please check why the solar panel is broken
5 | 9583f982-d7df-4aad-ab26-301d4a158cd7,3ccf474c-3881-44b7-99fb-59a2a4668418,2022-09-04T13:00:00Z,Bradley Flowers,What exactly is wrong?
6 |
--------------------------------------------------------------------------------
/tests/incidents-app/db/data/sap.capire.incidents-Incidents.csv:
--------------------------------------------------------------------------------
1 | ID,customer_ID,title,urgency_code,status_code
2 | 3b23bb4b-4ac7-4a24-ac02-aa10cabd842c,1004155,Inverter not functional,H,C
3 | 3a4ede72-244a-4f5f-8efa-b17e032d01ee,1004161,No current on a sunny day,H,N
4 | 3ccf474c-3881-44b7-99fb-59a2a4668418,1004161,Strange noise when switching off Inverter,M,N
5 | 3583f982-d7df-4aad-ab26-301d4a157cd7,1004100,Solar panel broken,H,I
--------------------------------------------------------------------------------
/tests/incidents-app/db/data/sap.capire.incidents-Status.csv:
--------------------------------------------------------------------------------
1 | code;descr;criticality
2 | N;New;3
3 | A;Assigned;2
4 | I;In Process;2
5 | H;On Hold;3
6 | R;Resolved;2
7 | C;Closed;4
--------------------------------------------------------------------------------
/tests/incidents-app/db/data/sap.capire.incidents-Urgency.csv:
--------------------------------------------------------------------------------
1 | code;descr
2 | H;High
3 | M;Medium
4 | L;Low
--------------------------------------------------------------------------------
/tests/incidents-app/db/schema.cds:
--------------------------------------------------------------------------------
1 | using { cuid, managed, sap.common.CodeList } from '@sap/cds/common';
2 |
3 | namespace sap.capire.incidents;
4 |
5 | /**
6 | * Customers using products sold by our company.
7 | * Customers can create support Incidents.
8 | */
9 | entity Customers : managed {
10 | key ID : String;
11 | firstName : String;
12 | lastName : String;
13 | name : String = firstName ||' '|| lastName;
14 | email : EMailAddress;
15 | phone : PhoneNumber;
16 | creditCardNo : String(16) @assert.format: '^[1-9]\d{15}$';
17 | addresses : Composition of many Addresses on addresses.customer = $self;
18 | incidents : Association to many Incidents on incidents.customer = $self;
19 | }
20 |
21 | entity Addresses : cuid, managed {
22 | customer : Association to Customers;
23 | city : String;
24 | postCode : String;
25 | streetAddress : String;
26 | }
27 |
28 |
29 | /**
30 | * Incidents created by Customers.
31 | */
32 | entity Incidents : cuid, managed {
33 | customer : Association to Customers;
34 | title : String @title: 'Title';
35 | urgency : Association to Urgency default 'M';
36 | status : Association to Status default 'N';
37 | conversation : Composition of many {
38 | key ID : UUID;
39 | timestamp : type of managed:createdAt;
40 | author : type of managed:createdBy;
41 | message : String;
42 | };
43 | }
44 |
45 | entity Status : CodeList {
46 | key code : String enum {
47 | new = 'N';
48 | assigned = 'A';
49 | in_process = 'I';
50 | on_hold = 'H';
51 | resolved = 'R';
52 | closed = 'C';
53 | };
54 | criticality : Integer;
55 | }
56 |
57 | entity Urgency : CodeList {
58 | key code : String enum {
59 | high = 'H';
60 | medium = 'M';
61 | low = 'L';
62 | };
63 | }
64 |
65 | type EMailAddress : String;
66 | type PhoneNumber : String;
67 |
--------------------------------------------------------------------------------
/tests/incidents-app/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@capire/incidents",
3 | "version": "1.0.0",
4 | "dependencies": {
5 | "@cap-js/attachments": "file:../../."
6 | },
7 | "cds": {
8 | "requires": {
9 | "auth": {
10 | "[development]": {
11 | "users": {
12 | "alice": {
13 | "roles": [
14 | "support",
15 | "admin"
16 | ]
17 | },
18 | "bob": {
19 | "roles": [
20 | "support"
21 | ]
22 | }
23 | }
24 | }
25 | },
26 | "attachments": {
27 | "kind": "db",
28 | "scan": false
29 | }
30 | }
31 | },
32 | "private": true
33 | }
34 |
--------------------------------------------------------------------------------
/tests/incidents-app/srv/services.cds:
--------------------------------------------------------------------------------
1 | using { sap.capire.incidents as my } from '../db/schema';
2 |
3 | /**
4 | * Service used by support personell, i.e. the incidents' 'processors'.
5 | */
6 | service ProcessorService {
7 | entity Incidents as projection on my.Incidents;
8 | entity Customers @readonly as projection on my.Customers;
9 | }
10 |
11 | /**
12 | * Service used by administrators to manage customers and incidents.
13 | */
14 | service AdminService {
15 | entity Customers as projection on my.Customers;
16 | entity Incidents as projection on my.Incidents;
17 | }
18 |
19 | annotate ProcessorService.Incidents with @odata.draft.enabled;
20 | annotate ProcessorService with @(requires: 'support');
21 | annotate AdminService with @(requires: 'admin');
22 |
--------------------------------------------------------------------------------
/tests/incidents-app/srv/services.js:
--------------------------------------------------------------------------------
1 | const cds = require('@sap/cds')
2 | const { SELECT } = cds.ql
3 |
4 | class ProcessorService extends cds.ApplicationService {
5 | /** Registering custom event handlers */
6 | init() {
7 | this.before('UPDATE', 'Incidents', req => this.onUpdate(req))
8 | this.before(['CREATE', 'UPDATE'], 'Incidents', req => this.changeUrgencyDueToSubject(req.data))
9 | return super.init()
10 | }
11 |
12 | changeUrgencyDueToSubject(data) {
13 | if (data) {
14 | const incidents = Array.isArray(data) ? data : [data]
15 | incidents.forEach(incident => {
16 | if (incident.title?.toLowerCase().includes('urgent')) {
17 | incident.urgency = { code: 'H', descr: 'High' }
18 | }
19 | })
20 | }
21 | }
22 |
23 | /** Custom Validation */
24 | async onUpdate(req) {
25 | const { status_code } = await SELECT.one(req.subject, i => i.status_code).where({ ID: req.data.ID })
26 | if (status_code === 'C') {
27 | return req.reject(`Can't modify a closed incident`)
28 | }
29 | }
30 | }
31 |
32 | module.exports = { ProcessorService }
33 |
--------------------------------------------------------------------------------
/tests/integration/attachments-non-draft.test.js:
--------------------------------------------------------------------------------
1 | const path = require("path");
2 | const fs = require("fs");
3 | const cds = require("@sap/cds");
4 | const { commentAnnotation, uncommentAnnotation } = require("../utils/modify-annotation");
5 |
6 | const servicesCdsPath = path.resolve(__dirname, '../incidents-app/srv/services.cds');
7 | const annotationsCdsPath = path.resolve(__dirname, '../incidents-app/app/incidents/annotations.cds');
8 | const linesToComment = [
9 | 'annotate ProcessorService.Incidents with @odata.draft.enabled;',
10 | 'annotate service.Incidents with @odata.draft.enabled;'
11 | ];
12 |
13 | beforeAll(async () => {
14 | await commentAnnotation(servicesCdsPath, linesToComment);
15 | await commentAnnotation(annotationsCdsPath, linesToComment);
16 | });
17 |
18 | const app = path.resolve(__dirname, "../incidents-app");
19 | const { expect, axios } = require("@cap-js/cds-test")(app);
20 |
21 | axios.defaults.auth = { username: "alice" };
22 | jest.setTimeout(5 * 60 * 1000);
23 |
24 | let attachmentID = null;
25 | let incidentID = "3ccf474c-3881-44b7-99fb-59a2a4668418";
26 |
27 | afterAll(async () => {
28 | await uncommentAnnotation(servicesCdsPath, linesToComment);
29 | await uncommentAnnotation(annotationsCdsPath, linesToComment);
30 | });
31 |
32 | describe("Tests for uploading/deleting and fetching attachments through API calls with non draft mode", () => {
33 | beforeAll(async () => {
34 | cds.env.requires.db.kind = "sql";
35 | cds.env.requires.attachments.kind = "db";
36 | await cds.connect.to("sql:my.db");
37 | await cds.connect.to("attachments");
38 | cds.env.requires.attachments.scan = false;
39 | cds.env.profiles = ["development"];
40 | });
41 |
42 | it("should create attachment metadata", async () => {
43 | const response = await axios.post(
44 | `/odata/v4/processor/Incidents(${incidentID})/attachments`,
45 | { filename: "sample.pdf" },
46 | { headers: { "Content-Type": "application/json" } }
47 | );
48 | expect(response.status).to.equal(201);
49 | expect(response.data).to.have.property("ID");
50 | attachmentID = response.data.ID;
51 | });
52 |
53 | it("should upload attachment content", async () => {
54 | const fileContent = fs.readFileSync(path.join(__dirname, 'content/sample.pdf'));
55 | const response = await axios.put(
56 | `/odata/v4/processor/Incidents(${incidentID})/attachments(up__ID=${incidentID},ID=${attachmentID})/content`,
57 | fileContent,
58 | {
59 | headers: {
60 | "Content-Type": "application/pdf",
61 | "Content-Length": fileContent.length
62 | }
63 | }
64 | );
65 | expect(response.status).to.equal(204);
66 | });
67 |
68 | it("should list attachments for incident", async () => {
69 | await new Promise(resolve => setTimeout(resolve, 5000));
70 | const response = await axios.get(
71 | `/odata/v4/processor/Incidents(ID=${incidentID})/attachments`
72 | );
73 | expect(response.status).to.equal(200);
74 | expect(response.data.value[0].up__ID).to.equal(incidentID);
75 | expect(response.data.value[0].filename).to.equal("sample.pdf");
76 | expect(response.data.value[0].content).to.be.undefined;
77 | expect(response.data.value[0].ID).to.equal(attachmentID);
78 | expect(response.data.value[0].status).to.equal("Clean");
79 | });
80 |
81 | it("Fetching the content of the uploaded attachment", async () => {
82 | const response = await axios.get(
83 | `/odata/v4/processor/Incidents(ID=${incidentID})/attachments(up__ID=${incidentID},ID=${attachmentID})/content`,
84 | { responseType: 'arraybuffer' }
85 | );
86 | expect(response.status).to.equal(200);
87 | expect(response.data).to.exist;
88 | expect(response.data.length).to.be.greaterThan(0);
89 |
90 | const originalContent = fs.readFileSync(path.join(__dirname, 'content/sample.pdf'));
91 | expect(Buffer.compare(response.data, originalContent)).to.equal(0);
92 | });
93 |
94 | it("Deleting the uploaded attachment", async () => {
95 | const response = await axios.delete(
96 | `/odata/v4/processor/Incidents(ID=${incidentID})/attachments(up__ID=${incidentID},ID=${attachmentID})`
97 | );
98 | expect(response.status).to.equal(204);
99 | });
100 |
101 | it("Verifying the attachment is deleted", async () => {
102 | try {
103 | await axios.get(
104 | `/odata/v4/processor/Incidents(ID=${incidentID})/attachments(up__ID=${incidentID},ID=${attachmentID})`
105 | );
106 | } catch (err) {
107 | expect(err.response.status).to.equal(404);
108 | }
109 | });
110 | });
111 |
--------------------------------------------------------------------------------
/tests/integration/attachments.test.js:
--------------------------------------------------------------------------------
1 | const cds = require("@sap/cds");
2 | const path = require("path");
3 | const app = path.resolve(__dirname, "../incidents-app");
4 | const { expect, axios, GET, POST, DELETE } = require("@cap-js/cds-test")(app);
5 | const { RequestSend } = require("../utils/api");
6 | const { createReadStream } = cds.utils.fs;
7 | const { join } = cds.utils.path;
8 |
9 | axios.defaults.auth = { username: "alice" };
10 | jest.setTimeout(5 * 60 * 1000);
11 |
12 | let utils = null;
13 | let sampleDocID = null;
14 | let incidentID = null;
15 |
16 | describe("Tests for uploading/deleting attachments through API calls - in-memory db", () => {
17 | beforeAll(async () => {
18 | cds.env.requires.db.kind = "sql";
19 | cds.env.requires.attachments.kind = "db";
20 | await cds.connect.to("sql:my.db");
21 | await cds.connect.to("attachments");
22 | cds.env.requires.attachments.scan = false;
23 | cds.env.profiles = ["development"];
24 | sampleDocID = null;
25 | incidentID = "3ccf474c-3881-44b7-99fb-59a2a4668418";
26 | utils = new RequestSend(POST);
27 | });
28 | //Draft mode uploading attachment
29 | it("Uploading attachment in draft mode with scanning enabled", async () => {
30 | //function to upload attachment
31 | let action = await POST.bind(
32 | {},
33 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=false)/attachments`,
34 | {
35 | up__ID: incidentID,
36 | filename: "sample.pdf",
37 | mimeType: "application/pdf",
38 | content: createReadStream(join(__dirname, "content/sample.pdf")),
39 | createdAt: new Date(
40 | Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000
41 | ),
42 | createdBy: "alice",
43 | }
44 | );
45 |
46 | try {
47 | //trigger to upload attachment
48 | await utils.draftModeActions(
49 | "processor",
50 | "Incidents",
51 | incidentID,
52 | "ProcessorService",
53 | action
54 | );
55 | } catch (err) {
56 | expect(err).to.be.undefined;
57 | }
58 |
59 | //read attachments list for Incident
60 | try {
61 | const response = await GET(
62 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=true)/attachments`
63 | );
64 | //the data should have only one attachment
65 | expect(response.status).to.equal(200);
66 | expect(response.data.value.length).to.equal(1);
67 | //to make sure content is not read
68 | expect(response.data.value[0].content).to.be.undefined;
69 | sampleDocID = response.data.value[0].ID;
70 | } catch (err) {
71 | expect(err).to.be.undefined;
72 | }
73 | //read attachment in active table
74 | try {
75 | const response = await GET(
76 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=true)/attachments(up__ID=${incidentID},ID=${sampleDocID},IsActiveEntity=true)/content`
77 | );
78 | expect(response.status).to.equal(200);
79 | expect(response.data).to.not.be.undefined;
80 | } catch (err) {
81 | expect(err).to.be.undefined;
82 | }
83 |
84 |
85 | // Check Scanning status
86 | try {
87 | const response = await GET(
88 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=true)/attachments`
89 | );
90 | expect(response.status).to.equal(200);
91 | expect(response.data.value.length).to.equal(1);
92 | expect(response.data.value[0].status).to.equal("Scanning"); // Initial status should be Scanning
93 |
94 | } catch (err) {
95 |
96 | expect(err).to.be.undefined;
97 | }
98 |
99 | //Mocking scanning timer for at least 5 seconds
100 | await new Promise(resolve => setTimeout(resolve, 5000));
101 |
102 | //Check clean status
103 | try {
104 | const response = await GET(
105 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=true)/attachments`
106 | );
107 | expect(response.status).to.equal(200);
108 | expect(response.data.value.length).to.equal(1);
109 | expect(response.data.value[0].status).to.equal("Clean");
110 | } catch (err) {
111 | expect(err).to.be.undefined;
112 | }
113 | });
114 |
115 | //Deleting the attachment
116 | it("Deleting the attachment", async () => {
117 | //check the content of the uploaded attachment in main table
118 | try {
119 | const response = await GET(
120 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=true)/attachments(up__ID=${incidentID},ID=${sampleDocID},IsActiveEntity=true)/content`
121 | );
122 | expect(response.status).to.equal(200);
123 | } catch (err) {
124 | expect(err).to.be.undefined;
125 | }
126 | //delete attachment
127 | let action = await DELETE.bind(
128 | {},
129 | `odata/v4/processor/Incidents_attachments(up__ID=${incidentID},ID=${sampleDocID},IsActiveEntity=false)`
130 | );
131 | try {
132 | //trigger to delete attachment
133 | await utils.draftModeActions(
134 | "processor",
135 | "Incidents",
136 | incidentID,
137 | "ProcessorService",
138 | action
139 | );
140 | } catch (err) {
141 | expect(err).to.be.undefined;
142 | }
143 |
144 | //read attachments list for Incident
145 | try {
146 | const response = await GET(
147 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=true)/attachments`
148 | );
149 | //the data should have no attachments
150 | expect(response.status).to.equal(200);
151 | expect(response.data.value.length).to.equal(0);
152 | } catch (err) {
153 | expect(err).to.be.undefined;
154 | }
155 |
156 | //content should not be there
157 | await expect(GET(
158 | `odata/v4/processor/Incidents(ID=${incidentID},IsActiveEntity=true)/attachments(up__ID=${incidentID},ID=${sampleDocID},IsActiveEntity=true)/content`
159 | )).to.be.rejectedWith(/404/);
160 | });
161 | });
162 |
163 | describe("Tests for attachments facet disable", () => {
164 | beforeAll(async () => {
165 | cds.env.requires.db.kind = "sql";
166 | cds.env.requires.attachments.kind = "db";
167 | await cds.connect.to("sql:my.db");
168 | await cds.connect.to("attachments");
169 | cds.env.requires.attachments.scan = false;
170 | cds.env.profiles = ["development"];
171 | utils = new RequestSend(POST);
172 | });
173 |
174 | it("Checking attachments facet metadata when @attachments.disable_facet is disabled", async () => {
175 | try {
176 | const res = await GET(
177 | `odata/v4/processor/$metadata?$format=json`
178 | );
179 | expect(res.status).to.equal(200);
180 | const facets = res.data.ProcessorService.$Annotations["ProcessorService.Incidents"]["@UI.Facets"];
181 | const attachmentsFacetLabel = facets.some(facet => facet.Label === 'Attachments')
182 | const attachmentsFacetTarget = facets.some(facet => facet.Target === 'attachments/@UI.LineItem')
183 | expect(attachmentsFacetLabel).to.be.true;
184 | expect(attachmentsFacetTarget).to.be.true;
185 | } catch (err) {
186 | expect(err).to.be.undefined;
187 | }
188 | });
189 |
190 | it("Checking attachments facet when @attachments.disable_facet is enabled", async () => {
191 | try {
192 | const res = await GET(
193 | `odata/v4/processor/$metadata?$format=json`
194 | );
195 | expect(res.status).to.equal(200);
196 | const facets = res.data.ProcessorService.$Annotations["ProcessorService.Incidents"]["@UI.Facets"];
197 | const hiddenAttachmentsFacetLabel = facets.some(facet => facet.Label === 'Attachments')
198 |
199 | //Checking the facet metadata for hiddenAttachments since its annotated with @attachments.disable_facet as enabled
200 | const hiddenAttachmentsFacetTarget = facets.some(facet => facet.Target === 'hiddenAttachments/@UI.LineItem')
201 | expect(hiddenAttachmentsFacetLabel).to.be.true;
202 | expect(hiddenAttachmentsFacetTarget).to.be.false;
203 | } catch (err) {
204 | expect(err).to.be.undefined;
205 | }
206 | })
207 | });
--------------------------------------------------------------------------------
/tests/integration/content/sample-1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/tests/integration/content/sample-1.jpg
--------------------------------------------------------------------------------
/tests/integration/content/sample-2.txt:
--------------------------------------------------------------------------------
1 | hello world
--------------------------------------------------------------------------------
/tests/integration/content/sample.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/tests/integration/content/sample.pdf
--------------------------------------------------------------------------------
/tests/non-draft-request.http:
--------------------------------------------------------------------------------
1 | @host = http://localhost:4004
2 | @auth = Basic YWxpY2U6d29uZGVybGFuZA==
3 |
4 | // Send the requests sequentially to avoid any conflicts
5 |
6 | ### Get list of all incidents
7 | # @name incidents
8 | GET {{host}}/odata/v4/processor/Incidents
9 | Authorization: {{auth}}
10 |
11 | ### Get list of attachments for a particular incident
12 | @incidentsID = {{incidents.response.body.value[2].ID}}
13 | # @name attachments
14 | GET {{host}}/odata/v4/processor/Incidents(ID={{incidentsID}})/attachments
15 | Authorization: {{auth}}
16 |
17 | ### Get attachments content
18 | @attachmentsID = {{attachments.response.body.value[1].ID}}
19 | GET {{host}}/odata/v4/processor/Incidents({{incidentsID}})/attachments(ID={{attachmentsID}})/content
20 | Authorization: {{auth}}
21 |
22 | ### Delete attachment
23 | DELETE {{host}}/odata/v4/processor/Incidents({{incidentsID}})/attachments(ID={{attachmentsID}})
24 | Authorization: {{auth}}
25 |
26 | ### Creating attachment (metadata request)
27 | # @name createAttachment
28 | POST {{host}}/odata/v4/processor/Incidents({{incidentsID}})/attachments
29 | Authorization: {{auth}}
30 | Content-Type: application/json
31 |
32 | {
33 | "filename": "sample-1.jpg"
34 | }
35 |
36 | ### Put attachment content (content request)
37 | @newAttachmentID = {{createAttachment.response.body.ID}}
38 | PUT {{host}}/odata/v4/processor/Incidents({{incidentsID}})/attachments(ID={{newAttachmentID}})/content
39 | Authorization: {{auth}}
40 | Content-Type: image/jpeg
41 |
42 | < ./integration/content/sample-1.jpg
43 |
44 | ### Fetching newly created attachment content
45 | GET {{host}}/odata/v4/processor/Incidents({{incidentsID}})/attachments(ID={{newAttachmentID}})/content
46 | Authorization: {{auth}}
47 |
--------------------------------------------------------------------------------
/tests/unit/validateAttachmentSize.test.js:
--------------------------------------------------------------------------------
1 | const { validateAttachmentSize } = require('../../lib/plugin');
2 |
3 | describe('validateAttachmentSize', () => {
4 | let req; // Define a mock request object
5 |
6 | beforeEach(() => {
7 | req = {
8 | headers: {},
9 | reject: jest.fn(), // Mocking the reject function
10 | };
11 | });
12 |
13 | it('should pass validation for a file size under 400 MB', () => {
14 | req.headers['content-length'] = '51200765';
15 |
16 | validateAttachmentSize(req);
17 |
18 | expect(req.reject).not.toHaveBeenCalled();
19 | });
20 |
21 | it('should reject for a file size over 400 MB', () => {
22 | req.headers['content-length'] = '20480000000';
23 |
24 | validateAttachmentSize(req);
25 |
26 | expect(req.reject).toHaveBeenCalledWith(403, 'File Size limit exceeded beyond 400 MB.');
27 | });
28 |
29 | it('should reject when content-length header is missing', () => {
30 | validateAttachmentSize(req);
31 |
32 | expect(req.reject).toHaveBeenCalledWith(403, 'Invalid Content Size');
33 | });
34 | });
35 |
36 |
--------------------------------------------------------------------------------
/tests/utils/api.js:
--------------------------------------------------------------------------------
1 | class RequestSend {
2 | constructor(post) {
3 | this.post = post;
4 | }
5 | async draftModeActions(
6 | serviceName,
7 | entityName,
8 | id,
9 | path,
10 | action,
11 | isRootCreated = false
12 | ) {
13 | if (!isRootCreated) {
14 | try {
15 | await this.post(
16 | `odata/v4/${serviceName}/${entityName}(ID=${id},IsActiveEntity=true)/${path}.draftEdit`,
17 | {
18 | PreserveChanges: true,
19 | }
20 | );
21 | } catch (err) {
22 | return err;
23 | }
24 | }
25 | try {
26 | await action();
27 | await this.post(
28 | `odata/v4/${serviceName}/${entityName}(ID=${id},IsActiveEntity=false)/${path}.draftPrepare`,
29 | {
30 | SideEffectsQualifier: "",
31 | }
32 | );
33 | await this.post(
34 | `odata/v4/${serviceName}/${entityName}(ID=${id},IsActiveEntity=false)/${path}.draftActivate`,
35 | {}
36 | );
37 | } catch (err) {
38 | return err;
39 | }
40 | }
41 | }
42 |
43 | module.exports = {
44 | RequestSend,
45 | };
46 |
--------------------------------------------------------------------------------
/tests/utils/modify-annotation.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs').promises;
2 |
3 | async function commentAnnotation(filePath, linesToComment) {
4 | try {
5 | const data = await fs.readFile(filePath, 'utf8');
6 |
7 | const lines = data.split('\n').map(line => {
8 | if (linesToComment.some(substring => line.includes(substring)) && !line.trim().startsWith('//')) {
9 | return `// ${line}`;
10 | }
11 | return line;
12 | });
13 |
14 | const modifiedData = lines.join('\n');
15 | await fs.writeFile(filePath, modifiedData, 'utf8');
16 | console.log(`File ${filePath} updated successfully.`);
17 | } catch (err) {
18 | console.error(`Error processing file ${filePath}:`, err);
19 | throw err;
20 | }
21 | }
22 |
23 | async function uncommentAnnotation(filePath, linesToUncomment) {
24 | try {
25 | const data = await fs.readFile(filePath, 'utf8');
26 |
27 | const lines = data.split('\n').map(line => {
28 | if (linesToUncomment.some(substring => line.includes(substring)) && line.trim().startsWith('//')) {
29 | return line.replace(/^\/\/\s?/, '');
30 | }
31 | return line;
32 | });
33 |
34 | const modifiedData = lines.join('\n');
35 | await fs.writeFile(filePath, modifiedData, 'utf8');
36 | console.log(`File ${filePath} updated successfully.`);
37 | } catch (err) {
38 | console.error(`Error processing file ${filePath}:`, err);
39 | throw err;
40 | }
41 | }
42 |
43 | module.exports = {
44 | commentAnnotation,
45 | uncommentAnnotation
46 | };
47 |
--------------------------------------------------------------------------------
/xmpl/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | # added by cds
3 | .cdsrc-private.json
4 |
--------------------------------------------------------------------------------
/xmpl/README.md:
--------------------------------------------------------------------------------
1 | ### Attachments sample
2 |
3 | This repository contains a sample CDS model extensions to demonstrate the CDS plugin [@cap-js/attachments](https://github.com/cap-js/attachments) on the [Incidents Management](https://github.com/cap-js/incidents-app) reference app for the new reuse types `Attachments`.
4 |
5 |
6 | ### References
7 |
8 | #### Incident Attachments:
9 | - Image by vecstock
10 |
11 |
12 |
13 | - All other sample data in attachments have been generated byusing [ChatGPT-3.5](https://www.openai.com/).
14 |
--------------------------------------------------------------------------------
/xmpl/db/attachments.cds:
--------------------------------------------------------------------------------
1 |
2 | using { sap.capire.incidents as my } from '@capire/incidents/db/schema';
3 | using { Attachments } from '@cap-js/attachments';
4 |
5 | extend my.Incidents with {
6 | attachments: Composition of many Attachments;
7 | }
8 |
--------------------------------------------------------------------------------
/xmpl/db/content/Broken Solar Panel.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/xmpl/db/content/Broken Solar Panel.jpg
--------------------------------------------------------------------------------
/xmpl/db/content/INVERTER FAULT REPORT.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/xmpl/db/content/INVERTER FAULT REPORT.pdf
--------------------------------------------------------------------------------
/xmpl/db/content/Inverter-error-logs.txt:
--------------------------------------------------------------------------------
1 | Timestamp: 2023-11-28 09:15:00
2 | Log: ERROR - Inverter malfunction detected. Output voltage is fluctuating outside normal range.
3 | Details: Voltage: 180V - 250V, Expected: 220V.
4 | Action taken: System shut down for safety. Investigating root cause.
5 |
6 | Timestamp: 2023-11-28 12:30:00
7 | Log: WARNING - Inverter temperature exceeding safe limits.
8 | Details: Temperature: 80°C, Safe limit: 60°C.
9 | Action taken: Reduced load to cool down the inverter. Monitoring closely.
10 |
11 | Timestamp: 2023-11-28 15:45:00
12 | Log: CRITICAL - Inverter failure. Complete loss of power.
13 | Details: No output voltage detected.
14 | Action taken: Emergency shutdown. Contacting maintenance for immediate inspection.
15 |
16 | Timestamp: 2023-11-29 08:00:00
17 | Log: ERROR - Inverter restart failure.
18 | Details: Attempted to restart the inverter, but unsuccessful.
19 | Action taken: Engaging maintenance team for on-site inspection and repairs.
20 |
21 | Timestamp: 2023-11-29 11:20:00
22 | Log: WARNING - Inverter communication error.
23 | Details: Loss of communication with the control system.
24 | Action taken: Reestablishing communication. Investigating possible control board issues.
--------------------------------------------------------------------------------
/xmpl/db/content/No_current.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/xmpl/db/content/No_current.xlsx
--------------------------------------------------------------------------------
/xmpl/db/content/Solar Panel Report.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cap-js/attachments/4a1ec2dc1f8fb4ec4600194e03db3c95cfb78cbf/xmpl/db/content/Solar Panel Report.pdf
--------------------------------------------------------------------------------
/xmpl/db/content/strange-noise.csv:
--------------------------------------------------------------------------------
1 | Timestamp,Noise_Level,Noise_Type
2 | 2023-11-28 08:00:00,75,Unknown
3 | 2023-11-28 08:05:00,82,Unusual Humming
4 | 2023-11-28 08:10:00,90,Mysterious Clicking
5 | 2023-11-28 08:15:00,78,Strange Whirring
6 | 2023-11-28 08:20:00,85,Unidentified Screech
7 | 2023-11-28 08:25:00,88,Odd Pulsating
8 | 2023-11-28 08:30:00,92,Eerie Rumbling
9 | 2023-11-28 08:35:00,79,Abnormal Hissing
10 | 2023-11-28 08:40:00,87,Unexplained Thumping
11 | 2023-11-28 08:45:00,95,Bizarre Chirping
--------------------------------------------------------------------------------
/xmpl/db/init.js:
--------------------------------------------------------------------------------
1 | const cds = require('@sap/cds/lib')
2 | module.exports = async function () {
3 |
4 | const attachments = await cds.connect.to('attachments')
5 | const { join } = cds.utils.path
6 | const { createReadStream } = cds.utils.fs
7 |
8 | const { 'sap.capire.incidents.Incidents.attachments': Attachments } = cds.model.entities
9 | await attachments.put (Attachments, [
10 | [ '3b23bb4b-4ac7-4a24-ac02-aa10cabd842c', 'INVERTER FAULT REPORT.pdf', 'application/pdf', cds.utils.uuid(),cds.utils.uuid(), 'Unscanned'],
11 | [ '3b23bb4b-4ac7-4a24-ac02-aa10cabd842c', 'Inverter-error-logs.txt', 'application/txt' , cds.utils.uuid(), cds.utils.uuid(),'Clean'],
12 | [ '3a4ede72-244a-4f5f-8efa-b17e032d01ee', 'No_Current.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', cds.utils.uuid(), cds.utils.uuid(),'Scanning'],
13 | [ '3ccf474c-3881-44b7-99fb-59a2a4668418', 'strange-noise.csv', 'text/csv', cds.utils.uuid(), cds.utils.uuid(),'Malware Detected'],
14 | [ '3583f982-d7df-4aad-ab26-301d4a157cd7', 'Broken Solar Panel.jpg', 'image/jpeg', cds.utils.uuid(), cds.utils.uuid(),'Clean'],
15 | ].map(([ up__ID, filename, mimeType, url, ID , status]) => ({
16 | up__ID, filename, mimeType, url, ID, status,
17 | content: createReadStream (join(__dirname, 'content', filename)),
18 | createdAt: new Date (Date.now() - Math.random() * 30*24*60*60*1000),
19 | createdBy: 'alice',
20 | })))
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/xmpl/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@capire/attachments-sample",
3 | "version": "1.0.0",
4 | "dependencies": {
5 | "@cap-js/attachments": "*",
6 | "@capire/incidents": "*",
7 | "@sap/cds": "*"
8 | },
9 | "devDependencies": {
10 | "@cap-js/sqlite": "*"
11 | },
12 | "private": true
13 | }
--------------------------------------------------------------------------------
/xmpl/srv/service.cds:
--------------------------------------------------------------------------------
1 | using from '@capire/incidents/app/services';
--------------------------------------------------------------------------------