Giter VIP home page Giter VIP logo

attachments's Introduction

REUSE status

Attachments Plugin

The @cap-js/attachments package is a CDS plugin 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.

Table of Contents

Setup

To enable attachments, simply add this self-configuring plugin package to your project:

 npm add @cap-js/attachments

In this guide, we use the Incidents Management reference sample app as the base application, to add Attachments type to the CDS model.

Note

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

Use Attachments

To use Attachments, simply add an element referring to the pre-defined Attachments type as follows:

using { Attachments } from '@cap-js/attachments';

entity Incidents {
  // ...
  attachments: Composition of many Attachments;
}

Test-drive Locally

With the steps above, we have successfully set up asset handling for our reference application. Let's see that in action. We can try out the scenarios where the attachments contents are stored locally in the database.

  1. Start the server:
  • Default scenario (In memory database):
    cds watch
  1. Navigate to the object page of the incident Solar panel broken:

    Go to Object page for incident Solar panel broken

  2. The Attachments type has generated an out-of-the-box Attachments table (see 1) at the bottom of the Object page:

Attachments Table

  1. 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:

Upload an attachment

  1. 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

Delete an attachment

Using SAP Object Store

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.

  1. Log in to Cloud Foundry:

    cf login -a <CF-API> -o <ORG-NAME> -s <SPACE-NAME>
  2. To bind to the service continue with the steps below.

    In the project directory, you can generate a new file _.cdsrc-private.json by running:

    cds bind objectstore -2 <INSTANCE>:<SERVICE-KEY> --kind s3

Using SAP Malware Scanning Service

For using SAP Malware Scanning Service, you must already have a service instance which you can access.

  1. To bind to the service continue with the steps below.

    cds bind malware-scanner -2 <INSTANCE>:<SERVICE-KEY>

By default, malware scanning is enabled for all profiles except development profile. You can configure malware scanning by setting:

"attachments": {
    "scan": true
}

Contributing

This project is open to feature requests/suggestions, bug reports etc. via GitHub 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.

Code of Conduct

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 at all times.

Licensing

Copyright 2024 SAP SE or an SAP affiliate company and contributors. Please see our LICENSE for copyright and license information. Detailed information including third-party components and their licensing/copyright information is available via the REUSE tool.

attachments's People

Contributors

muskansethi1 avatar mnkiefer avatar danjoa avatar ramindia avatar sidakphull avatar jeevitha011 avatar zahlii avatar chgeo avatar danschlachter avatar david-kunz avatar

Stargazers

Thorben avatar Steven Zifan Yin avatar Alexandre Giguere avatar Shitty Girl avatar Frank avatar t-O.y avatar Eduardo Fagundes avatar EgorT avatar Jason Scott avatar Oliver Klemenz avatar

Watchers

Nils Schnabel avatar  avatar 「ph1L」 avatar  avatar Eduardo Fagundes avatar  avatar Nick Josipovic avatar  avatar Christian Dinse avatar t-O.y avatar  avatar Nezzquikk avatar MURATA Masahiko avatar

attachments's Issues

Support for NodeJs version > 17

Context:

SAP BTP Cloud Foundry environment recommends using Node.js versions 18 and 20 for deployment. You can find more information on their recommendations here: SAP BTP CF Environment.

Issue:

When attempting to install the package with Node.js versions 18 or 20, the following warning is displayed:

npm WARN EBADENGINE Unsupported engine {
npm WARN EBADENGINE   package: '@cap-js/[email protected]',
npm WARN EBADENGINE   required: { node: '^17.0.0' },
npm WARN EBADENGINE   current: { node: 'v20.12.2', npm: '10.5.0' }
npm WARN EBADENGINE }

Request:

To ensure compatibility and leverage the latest Node.js features and security updates, I kindly request that the @cap-js/attachments package be updated to support Node.js versions 18 and 20.

This update would be highly beneficial for developers deploying applications in environments that recommend or require these versions.

CDS-TYPER TYPESCRIPT ERROR

Is your feature request related to a problem? Please describe.
I am using TypeScript in a SAP CAP project and converting services and entities defined in CDS to TypeScript using @cap-js/cds-typer.
However, since the definition of Attachments is not generated by cds-typer, an error occurs when running tsc.

Additional context
image

Error - Region is missing

Getting Error:
image

Change in Code - This Works

  async updateContentHandler(req, next) {
    if (req._path.endsWith("content")) {
      const response = await SELECT.from(req.target, { ID: req.data.ID }).columns("url");
      if (response?.url) {
        const Key = response.url;
        const input = {
          Bucket: this.bucket,
          Key,
          Body: req.data.content,
          Region: this.options.credentials.region
        };
        const multipartUpload = new Upload({
          // client: new S3Client({}),
          **client: this.client,**
          params: input,
        });
        // TODO: add malware scan
        // const stored = super.put (Attachments, metadata)
        await Promise.all([multipartUpload.done()]);
      }
    } else {
      next();
    }
  }

Note cannot be added in draft mode

Hi,

we have a CAP/Fiori Elements application with cap-js/attachment and deployed it to cloud foundry. We used object store to save the attachments.

The attachment association is added to an entity which is draft-enabled.

The attachment reuse UI is shown and I could successfully upload and save a text file. But when I edit the entity, add a note to the attachment and save the draft, I get an error.

The CF log shows me:
1279878","x_sf_correlation_id":"8470c2d2-c147-4415-778e-248eb64c1b7b","x_vcap_request_id":"8470c2d2-c147-4415-778e-248eb64c1b7b","request_id":"8470c2d2-c147-4415-778e-248eb64c1b7b","x_correlation_id":"8470c2d2-c147-4415-778e-248eb64c1b7b","timestamp":"2024-06-10T09:24:43.005Z","msg":"❗️Uncaught Transaction is already closed","stacktrace":["Error: Transaction is already closed","at /home/vcap/app/node_modules/@sap/cds/libx/_runtime/hana/execute.js:162:36","at Statement.handle (/home/vcap/app/node_modules/hdb/lib/protocol/Statement.js:91:3)","at handleReply (/home/vcap/app/node_modules/hdb/lib/Client.js:278:15)","at receive (/home/vcap/app/node_modules/hdb/lib/util/Queue.js:114:18)","at Connection.receive (/home/vcap/app/node_modules/hdb/lib/protocol/Connection.js:394:5)","at TLSSocket.ondata (/home/vcap/app/node_modules/hdb/lib/protocol/Connection.js:243:12)","at TLSSocket.emit (node:events:517:28)","at addChunk (node:internal/streams/readable:368:12)","at readableAddChunk (node:internal/streams/readable:341:9)","at Readable.push (node:internal/streams/readable:278:10)"],"numericSeverity":4,"layer":"cds","component_type":"application","container_id":"10.0.137.29","component_id":"9fb24712-c733-4732-b24e-8707faff7bb4","component_name":"poetry-slams-srv","component_instance":0,"source_instance":0,"organization_name":"ch-erp","organization_id":"d3b1e418-87fc-474e-a57a-194a92487727","space_name":"dev","space_id":"8274bb9f-a1db-485d-ad43-eb13ff033823","tenant_subdomain":"ch-erp-prv","type":"log"}

Could you please give advice?

Best regards,
Christine

Enhancement requests and questions regarding attachment library for CAP applications

Hello team,

we have been exploring the new attachment library for CAP applications, and we really like how easy it is to integrate it into existing applications! We have some question regarding the usage internally at SAP:

  • The library injects the UI annotation for the attachments. We would like to have an option to influence this behaviour, e.g. to hide certain columns or to show the attachments somewhere else on the object page.
  • We have use cases where only one attachment is allowed. Is there currently a possibility to control/restrict the number of attachments.
  • For security reasons we have to use mTLS authentication where ever possible. The library is internally using Basic Authentication for consuming the malware scanning service. Is there a way to change this?
  • We have the guideline that files should be scanned for virus during the upload and during the download stage as well. Is it possible to enforce this in the library?

Cannot add custom fields/logic to Attachments entity

using {Attachments} from '@cap-js/attachments';
// also using {Attahcment as BaseAttachments} and naming our entity Attachments : BaseAttachments same error


entity UIAttachments : Attachments {
    approvalStatus                  : Association to cdh.Status @readonly;
}

entity Bla {
  attachments                             : Composition of many UIAttachments;
}

Results in:

[cds] - ❗️Uncaught TypeError: Cannot read properties of undefined (reading 'xpr')
    at _addKeysToData (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/utils/data.js:67:22)
    at _addKeysToData (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/utils/data.js:69:12)
    at _addForeignKeys (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/utils/data.js:159:5)
    at getData (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/utils/data.js:284:5)
    at new ODataRequest (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/ODataRequest.js:141:20)
    at /Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/handlers/create.js:27:13
    at /Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/core/Dispatcher.js:135:7
    at new Promise (<anonymous>)
    at Dispatcher._handle (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/core/Dispatcher.js:134:12)
    at Dispatcher.dispatch (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/core/Dispatcher.js:97:21) {
  id: '1350143',
  level: 'ERROR',
  timestamp: 1718184547532
}

Event handler code ignored in Cloud Foundry environment

This issue is related to the following one:
#50

Issue

After adding @cap-js/attachment plugin, event handler stopped working in Cloud Foundry environment.

Project Setup

https://github.com/miyasuta/cap-attachment

  • In a CAP project created simply via cds add tiny-samples, I've added the following event handler file.
const cds = require('@sap/cds');

module.exports = class CatalogService extends cds.ApplicationService {
    async init () {
        this.after('READ', 'Books', each => {
            each.title = each.title + ' --added by event handler';
        })
        return super.init();
    }
}
  • @cap-js/attachment plugin has been enabled as per the guidance, and it is working without an issue.
using { my.bookshop as my } from './data-model';
using { Attachments } from '@cap-js/attachments';

extend my.Books with { attachments: Composition of many Attachments }
  • For deployment, I have added the following settings to the package.json file, as I don't have an entitlement for SAP Object Store in my trial account.
    "cds": {
        "requires": {
            "[production]": {
                "db": "hana",
                "auth": "xsuaa"
            },
            "attachments": {
                "kind": "db"
            }             
        }
    }

Result

The even handler is working fine in the local environment. I could see the output as below:
image

However, after this project was deployed to the Cloud Foundry, the event hander stopped working as if the source code itself has been removed. The following screenshot shows a response from the deployed app captured with Postman.
image

Am I missing any settings, or for productive environment, only SAP Object Store is supported?

Update @sap/cds version to 8

Hi colleagues,
cap-js/sdm team tried to update the @sap/cds version to 8, but we were getting error in build. Error was of version mismatch because cap-js/attachments repository uses cds v7, and attachments is added as a dependency in cap-js/sdm plugin.
Please refer this comment from @chgeo cap-js/sdm#44 (comment)

All plugins needs to be on @sap/cds v8.

Without malware scanner, setTimeout to "mock" the scan results in "no such table" exception when running e.g. in jest test suite

https://github.com/cap-js/attachments/blob/main/lib/malwareScanner.js#L26

Due to the (unawaited) setTimeout call, it can happen that the UPDATE() statement is attempted in the background after test teardown, resulting in an error as follows:

SqliteError: no such table: sapit_cdh_unintegrated_UnintegratedDataRequests_attachments in:
    UPDATE sapit_cdh_unintegrated_UnintegratedDataRequests_attachments AS attachments SET status=?,ID=?,modifiedAt=coalesce(ISO(NULL), session_context('$now')),modifiedBy=coalesce(NULL, session_context('$user.id')) WHERE attachments.ID = ?

Our test setup basically looks as follows:

beforeEach() => {
await data.delete();
await POST('.../attachments', {mimeType: 'image/png', filename: 'test.png'});
}

it('put content', async () => {
await PUT('.../attachments(ID=...)/content', 'mock content');
// this will trigger setTimeout() call internally

await new Promise<void>((res, rej) => setTimeout((_) => res(), 5100));
// this line MUST be contained to make sure the test can only tear down once the setTimeout has triggered, otherwise we risk the above race condition/error
}

Attchment plugin not working

Hello,

Thanks for this repository first of all. It worked for me till 27th April 2024. I found there is a new version deployed after. No more the plug-in works!

npm i @cap-js/attachments@*1.0.1 doesn't install the previous version too. Kindly check once.

Currently I see the below error appears while I try to link up to my existing CAP Project. I confirm I haven't made any single change to my CAP project.

issue - plugin

issue - npm

  • Thanks, Somnath

[Version: 1.1.5 ] Not possible to save attachments

Hi Team,

the attachment field is added in schema and the entity is odata_draft_enabled.

using {
  managed,
  cuid
} from '@sap/cds/common';

using { Attachments } from '@cap-js/attachments';

namespace supplierportal.playground;

@cds.persistence.journal
entity Toys : cuid, managed {
  name   : String;
  status : Composition of one Statuses;
  attachments: Composition of many Attachments;
}

We have following dependencies.

    "@cap-js/attachments": "1.1.5",
    "@sap-cloud-sdk/connectivity": "^3.16.0",
    "@sap-cloud-sdk/http-client": "3.16.0",
    "@sap/cds": "7.9.4",
    "@sap/hana-client": "2.20.20",
    "@sap/xssec": "^4",
    "express": "4.19.2",
    "npm": "10.7.0",
    "sqlite3": "5.1.7"

The attachment section is visible and looks good.
image

As soon as we save the attachment, we get an "Internal Server Error" and following logs are available.
image
image

Any ideas?

[Version: ] Attachments with no name and not able to download it

Describe the bug
A clear and concise description of what the bug is.

I created a sample CAP app in BAS with only 1 entity named Books
I added a composition relationship to the attachment entity

In my service, I have exposed the books entity and added
annotated Books with @odata.draft.enabled;

I am running the app with the hybrid profile from BAS
cds watch --profile hybrid

the attachments UI is there below my books table
however when I upload an attachment, the attachment name is not display and I can after that download it or open it
also if I tried to update the filed note, I got an error
"Cannot read properties of undefined (reading 'endsWith')"

I am using Object Store with Amazon S3 bucket

thanks

Screenshots
If applicable, add screenshots to help explain your problem.
Screenshot 2024-08-15 at 4 00 53 PM
Screenshot 2024-08-15 at 5 39 27 PM

CAP/Fiori Elements application error during save

Hi,

we have a CAP/Fiori Elements application with cap-js/attachment and deployed it to cloud foundry. We used object store to save the attachments.

The attachment association is added to an entity which is draft-enabled

The attachment reuse UI is shown and I could successfully upload a text file, but when I save the draft, I get an error.

The CF log shows me:
46f4e81c0e6","timestamp":1717600545660,"msg":"sql syntax error: incorrect syntax near ")": line 1 col 100 (at pos 100)","message":"sql syntax error: incorrect syntax near ")": line 1 col 100 (at pos 100)","code":257,"sqlState":"HY000","position":100,"query":"SELECT url AS "url" FROM localized_PoetrySlamService_PoetrySlams_attachments ALIAS_1 WHERE ID IN ( )"

In chrome, I get: Log-dbg.js:499 2024-06-05 17:15:45.205100 Failed to execute /PoetrySlams(ID=79ceab87-300d-4b66-8cc3-f82c679b77a1,IsActiveEntity=false)/PoetrySlamService.draftActivate(...) - Error: Communication error: 500 Internal Server Error

Could you please give advice?

Best regards,
Christine

Support for Azure Blob Storage

Hi Team,

I could see the support for s3 but I have a sub account in Azure landscape and we are using object-store with Azure blob storage.
I see this is not supported yet. Is anyone already working on it. Please clarify.

Thanks,
Sachin Srambickal

Local Dev: Status stays unscanned, can't open attachment

With SAPUI5 version 1.125.1 the status of an attachment stays in status unscanned in local development with scan : false.
When clicking on the uploaded attachment after save , it gives an error

<code>403</code>
<message>Unable to download the attachment as scan status is not clean.</message>

Cannot upload non-standard file types (e.g. .md files)

[odata] - PUT /unintegratedrequest-cockpit/UnintegratedDataRequests_attachments(up__ID=913b389d-77d4-4973-9c86-9ab108f6e3d4,ID=eed0a156-f3a8-4fe8-b2bd-da13f23e7aca,IsActiveEntity=false)/content 
[cds] - DeserializationError: Invalid value "undefined" in content-type header
    at RequestContentNegotiator.negotiate (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/format/RequestContentNegotiator.js:36:15)
    at DeserializingCommand.execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/DeserializingCommand.js:43:39)
    at CommandExecutor._execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:71:17)
    at /Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:81:18
    at PresetResponseHeadersCommand.execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/PresetResponseHeadersCommand.js:43:5)
    at CommandExecutor._execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:71:17)
    at /Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:81:18
    at LocaleNegotiatorCommand.execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/LocaleNegotiatorCommand.js:51:7)
    at CommandExecutor._execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:71:17)
    at /Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:81:18 {
  _rootCause: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined
      at new NodeError (node:internal/errors:399:5)
      at Function.from (node:buffer:339:9)
      at Function.parseContentTypeHeader (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-commons/http/HttpHeader.js:14:59)
      at RequestContentNegotiator.negotiate (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/format/RequestContentNegotiator.js:33:22)
      at DeserializingCommand.execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/DeserializingCommand.js:43:39)
      at CommandExecutor._execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:71:17)
      at /Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:81:18
      at PresetResponseHeadersCommand.execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/PresetResponseHeadersCommand.js:43:5)
      at CommandExecutor._execute (/Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:71:17)
      at /Users/***/PycharmProjects/cockpit/node_modules/@sap/cds/libx/_runtime/cds-services/adapter/odata-v4/okra/odata-server/invocation/CommandExecutor.js:81:18 {
    code: 'ERR_INVALID_ARG_TYPE'
  },
  id: '1955289',
  level: 'WARNING',
  timestamp: 1718184177894
}

With his request being send:

{
  "_priority": "High",
  "_resourceType": "xhr",
  "cache": {},
  "connection": "68280",
  "request": {
    "method": "PUT",
    "url": "http://localhost:4004/unintegratedrequest-cockpit/UnintegratedDataRequests_attachments(up__ID=913b389d-77d4-4973-9c86-9ab108f6e3d4,ID=efd48fab-f5db-499e-bc3d-d5debce40864,IsActiveEntity=false)/content",
    "httpVersion": "HTTP/1.1",
    "headers": [
      {
        "name": "Accept",
        "value": "application/json"
      },
      {
        "name": "Accept-Encoding",
        "value": "gzip, deflate, br, zstd"
      },
      {
        "name": "Accept-Language",
        "value": "de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7,tr;q=0.6,es;q=0.5"
      },
      {
        "name": "Authorization",
        "value": "Basic STAwMTAwMDo="
      },
      {
        "name": "Connection",
        "value": "keep-alive"
      },
      {
        "name": "Content-Length",
        "value": "1961"
      },
      {
        "name": "DNT",
        "value": "1"
      },
      {
        "name": "Host",
        "value": "localhost:4004"
      },
      {
        "name": "Origin",
        "value": "http://localhost:4004"
      },
      {
        "name": "Referer",
        "value": "http://localhost:4004/fiori.html"
      },
      {
        "name": "Sec-Fetch-Dest",
        "value": "empty"
      },
      {
        "name": "Sec-Fetch-Mode",
        "value": "cors"
      },
      {
        "name": "Sec-Fetch-Site",
        "value": "same-origin"
      },
      {
        "name": "User-Agent",
        "value": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
      },
      {
        "name": "sec-ch-ua",
        "value": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Google Chrome\";v=\"126\""
      },
      {
        "name": "sec-ch-ua-mobile",
        "value": "?0"
      },
      {
        "name": "sec-ch-ua-platform",
        "value": "\"macOS\""
      }
    ],
    "queryString": [],
    "headersSize": 1659,
    "bodySize": 0
  },
  "response": {
    "status": 400,
    "statusText": "Bad Request",
    "httpVersion": "HTTP/1.1",
    "headers": [
      {
        "name": "Connection",
        "value": "keep-alive"
      },
      {
        "name": "Content-Length",
        "value": "223"
      },
      {
        "name": "Date",
        "value": "Wed, 12 Jun 2024 09:24:33 GMT"
      },
      {
        "name": "Keep-Alive",
        "value": "timeout=5"
      },
      {
        "name": "OData-Version",
        "value": "4.0"
      },
      {
        "name": "X-Powered-By",
        "value": "Express"
      },
      {
        "name": "access-control-allow-origin",
        "value": "http://localhost:4004"
      },
      {
        "name": "content-type",
        "value": "application/json;odata.metadata=minimal"
      },
      {
        "name": "x-correlation-id",
        "value": "9f822bab-f850-4ffc-9514-c8c6ec0f7bf5"
      }
    ],
    "cookies": [],
    "content": {
      "size": 223,
      "mimeType": "application/json",
      "compression": 0
    },
    "redirectURL": "",
    "headersSize": 339,
    "bodySize": 223,
    "_transferSize": 562,
    "_error": null,
    "_content": {}
  },
  "serverIPAddress": "[::1]",
  "startedDateTime": "2024-06-12T09:24:33.136Z",
  "time": 7.392999948933721,
  "timings": {
    "blocked": 1.6189999473318457,
    "dns": -1,
    "ssl": -1,
    "connect": -1,
    "send": 0.14100000000000001,
    "wait": 4.957999984093011,
    "receive": 0.6750000175088644,
    "_blocked_queueing": 1.0479999473318458
  }
}

[PROPOSAL] A generic implementation for object store

This is a proposal request to have a generic implementation of object store such that irrespective of blob store or s3 or any other in future, developers will only be exposed to common methods to upload, download, list or delete.

We did a similar implementation covering both Azure blob and AWS S3 for now. But that was only specific to using object store as a plugin (not along with this broader implementation of having attachments). It makes sense to merge it here if it also makes sense for you.

Would you like to have a look at that repository? And once it make sense overall, I can request for a merge of the implementation with the necessary changes.

Attachments should not be set to scanning when malware scanning is disabled

After uploading a new attachment, its status should never be set to scanning when malware scanning is disabled. An unaware user would not know that it is disabled and as such would be mislead by the status "Scanning". The attachment should therefor always be in Scan Status "Unscanned" if malware scanning is disabled.

With that an attachment should be downloadable if malware scanning is disabled an scan status is set to "Unscanned"

/lib/malwareScanner.js

async function scanRequest(Attachments, key) {
  const scanEnabled = cds.env.requires?.attachments?.scan ?? true
  const AttachmentsSrv = await cds.connect.to("attachments")
  
  let draftEntity, activeEntity
  if (Attachments.isDraft) {
    draftEntity = Attachments
    activeEntity = Attachments.actives
  } else {
    activeEntity = Attachments
  }

  let currEntity = draftEntity == undefined ? activeEntity : draftEntity

  await updateStatus(AttachmentsSrv, key, "Scanning", currEntity, draftEntity, activeEntity)

  if (!scanEnabled) {
    setTimeout(async () => {
      DEBUG?.('Malware scanning is disabled. Setting scan status to Clean.')
      await updateStatus(AttachmentsSrv, key, "Clean", currEntity, draftEntity, activeEntity)
    }, 5000)

    return
  }
  ...

Malware Scanner Throws Error

Hi,

we have a CAP/Fiori Elements application with cap-js/attachment and deployed it to cloud foundry. We used object store to save the attachments.

The attachment association is added to an entity which is draft-enabled. The attachment reuse UI is shown and I could upload a text file, but I see an error in console and when I save the draft, I get an error.

The CF log shows me:
06T07:49:03.064Z","msg":"❗️Uncaught Found 0 matching services","stacktrace":["VError: Found 0 matching services","at Object.serviceCredentials (/home/vcap/app/node_modules/@sap/xsenv/lib/xsservices.js:121:11)","at getCredentials (/home/vcap/app/node_modules/@cap-js/attachments/lib/malwareScanner.js:91:16)","at scanRequest (/home/vcap/app/node_modules/@cap-js/attachments/lib/malwareScanner.js:31:23)","at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"],"jse_shortmsg":"Found 0 matching services","jse_info":{},"message":"Found 0 matching

The file is nevertheless there and after some time, the save works.

Could you please give advice?

Best regards,
Christine

[CONTRIBUTE] Kind DMS - SAP Document Management Serivce

Hi SAP,

i will like to contribute with the attachments for the service DMS in SAP BTP. I just forked and I want some help starting to develop this contribution.

The specific reason or objective is because SAP Build Apps uses the upload only in DMS and not in object store. Because, the instances sometimes needs actions that calls an action to a CAP service and is necessary to put the DMS data to the entity so the CAP App know's where is the uploaded file is in DMS. I hope i'm not wrong.

regards,
Cesar Felce

Attachements plugin with cds typer throws error

When trying to integrate the attachments plugin into our CAP application we get the following errors:

`@cds-models/application/index.ts:414:46 - error TS2344: Type 'Attachments' does not satisfy the constraint 'readonly any[]'.
Type 'Attachments' is missing the following properties from type 'readonly any[]': length, concat, join, slice, and 20 more.
414 attachments?: __.Composition.of.many<_.Attachments>;

and:

@cds-models/index.ts:81:78 - error TS2552: Cannot find name '_AttachmentAspect'. Did you mean '_AttachmentsAspect'?
81 export class Attachments extends _managedAspect(_cuidAspect(_MediaDataAspect(_AttachmentAspect(__.Entity)))) {static drafts: typeof Attachments}`

The project is implemented with typescript and is using cds-typer plugin from sap (https://github.com/cap-js/cds-typer) to define types. After we integrated the attachements plugin via npm add @cap-js/attachments, then integrated it into our model and tryed to deploye it to our sqlite data base. We get the error written above.

We are using the following versions:

  • cds: 7.9.2
  • cds-dk: 7.9.3
  • @cap-js/cds-typer: 0.21.2
  • @cap-js/attachements: 1.1.1

SAPUI5 Version conflicts (1.123 and 1.124)

Hello there,

I've recently noticed that the cap-js/attachments plugin is incompatible with the SAPUI5 version 1.123 and 1.124 (1.125 works fine).
Specifically there seems to be an issue with missing ui5 functions, which leads to the app not loading:
image

Sometimes also an duplicate id error is thrown:
image

Since I've only been able to find a reference that UI5 version 1.121.0 or higher (^1.121.0) is required, this version incompatibility should probably be documented somewhere.

Versions:
@cap-js/attachments: 1.0.2
@cap-js/cds-types: 0.2.0
@sap/cds: 7.9.2
@sap/cds-compiler: 4.9.4
@sap/cds-dk: 7.6.0
@sap/cds-dk (global): 7.9.3
@sap/cds-fiori: 1.2.3

Best regards
Timo

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.