node.js – Api da vimeo em node para upload de vídeos return error “source object may only be an instance of Buffer or Readable in this environment”

Antes de tudo, já vou descartar pontos de possíveis erros:

1 – Minha conta é Premium e tem permissão para upload de vídeos pela api: https://i.imgur.com/LEo25QJ.png

2 – Já tentei utilizar outros fromatos de arquivo, como blob, porém recebo outro erro basciamene falando que não é possivel encontraro local do arquivo;

3 – Já tentei passar o file como buffer utilizando req.file.buffer , porem recebo novos erros como o da imagem a seguir: https://i.imgur.com/7tDn7aa.png

Estou tentando pegar um arquivo através de um formulário e envia-lo para a vimeo através da vimeo-api em Node;

Enfim, segue a implementação do meu código:

Front-end com chamada do meu endpoint:

    const startUploadFinal = () => {
    const formData = new FormData();
    formData.append('video_file', currentFile);

    localhost.post('vimeo/blob', formData, {
      headers: {
        'Content-type': 'multipart/form-data',
        access_token: `voitto-token ${localStorage.getItem('oauth_token')}`
      }
    });
   };

Router for my endpoint:

import { Router } from 'express';
import Vimeo from '../../app/controller/vimeoController';
import AuthMiddleware from '../../app/middleware/auth';
import upload from '../../config/multerConfig';

const routes = new Router();

routes.post(
  '/vimeo',
  upload.single('video_file'),
  AuthMiddleware,
  Vimeo.upload
);

export default routes;

Upload config with multex:

import multer from 'multer';

const storage = multer.memoryStorage();
const upload = multer({ storage });

module.exports = upload;

Meu endpoint:

    async upload(req, res) {
     const client = new Vimeo(client_id, client_secret, fixedToken);
     console.log('File:', req.file);
     console.log('Size file:', req.file.size);
     client.upload(
      req.file,
      {
        name: 'Testing',
        description: 'Tescription Testing',
        'upload.size': req.file.size,
        'upload.approach': 'tus',
      },
      function (uri) {
        console.log('File upload completed. Your Vimeo URI is:', uri);
      },
      function (bytesUploaded, bytesTotal) {
        const percentage = ((bytesUploaded / bytesTotal) * 100).toFixed(2);
        console.log(bytesUploaded, bytesTotal, `${percentage}%`);
      },
      function (error) {
        console.log(`${error}`);
      }
     );
  }

Print dos dados no endpoint e erro final apresentado:

Image of error

Alguém consegue me informar o que estou fazendo de errado?

javascript – Displaying a date object on the page in a readable format – React

I have a form that the user is filling out that includes a date that the user can set.
At the moment the date objects are in the following format
"2021-07-29T00:16:20.391Z"

using this answer I was able to convert it with the new Date() constructor
let readable = new Date(date)
At this point the date is Sun Aug 01 2021 17:16:20 GMT-0700 (Pacific Daylight Time) I can see it in the browser console

This format is what I want, however it is an object so I cannot display it on the page like I need to.
So I use JSON.Stringify()
let stringTime = JSON.stringify(readable)

This allows the time to be shown on the page, however it reverts to the original format of "2021-07-29T00:16:20.391Z" I can’t for the life of me get the readable Object to display on the page without reverting to the hard to read date format.

What am I missing here? Thank you in advance for your help.

python – What is the most maintainable and readable method to store and reference parameterized SQL queries?

A buddy of mine and I are going back and forth on where to store our parameterized SQL queries in our classes. We aren’t using an ORM because they are notorious for creating performance issues and performance is critical in this application.

He prefers the query to be stored where it is executed. For instance:

class SomeClass:

    def some_function(self, x, y):
        query = "SELECT a, b, c FROM table WHERE q=$1 AND z=$2"
        stmt = conn.prepare(query)
        return stmt.fetch(x, y)

I prefer to define the query as a class property then reference it:

class SomeClass:

    SELECT_SOMETHING = "SELECT a, b, c FROM table WHERE q=$1 AND z=$2"

    def some_function(self, x, y):
        stmt = conn.prepare(SomeClass.SELECT_SOMETHING)
        return stmt.fetch(x, y)

In a large application with dozens of classes and queries, and several large queries, which style easier to read and maintain?

c++ – How to make the initialization of the mocks more readable?

In an Arduino project, I’m using some code which is a slightly modified version of a public library. I made several modifications to it:

  • I performed some minor changes I needed to make the code work.
  • Instead of relying on Arduino library, it makes use of the wrappers, which can be mocked in the tests.
  • I started adding the actual tests of the class.

When writing the tests, I was quite surprised by their complexity—and how unreadable and unmaintainable they are. The tested code itself doesn’t seem that complicated: granted, there are multiple possible branches, but it still is relatively basic. Each test of a given execution path seems however overly complex, and doesn’t translate much of what the code is doing. I’m pretty sure that when I will found those tests six months later, I would have no idea what they are doing, and shall spend a lot of time trying to figure out how they work. Similarly, any change in the actual code would lead to painful changes in the tests.

Here they are. At least the first five tests I wrote—a few dozens more need to be written in order to cover all the possible code execution paths. The last two tests are particularly illustrative.

What can be done to make them more bearable? Am I doing it completely wrong? Should I be implementing some sort of DSL just for the tests?

#include "../src/wrappers/AHT21WrapperArduino.h"
#include "../src/wrappers/WireWrapper.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>

using ::testing::Return;

const int8_t StatusNone = 0b00000000;
const int8_t StatusCalibrated = 0b00001000;
const int8_t StatusBusy = 0b10000000;

class MockTime: public Time {
 public:
    MOCK_METHOD(long, now, (), (override));
    MOCK_METHOD(void, pause, (unsigned long milliseconds), (override));
};

class MockWire: public WireWrapper {
 public:
    MOCK_METHOD(void, begin, (), (override));
    MOCK_METHOD(void, beginTransmission, (uint8_t address), (override));
    MOCK_METHOD(uint8_t, endTransmission, (), (override));
    MOCK_METHOD(uint8_t, requestFrom, (uint8_t address, uint8_t quantity), (override));
    MOCK_METHOD(int, available, (), (override));
    MOCK_METHOD(int, read, (), (override));
    MOCK_METHOD(size_t, write, (uint8_t data), (override));
};

TEST(AHT21WrapperArduino, Init) {
    // Standard initialization, where everything goes as expected.
    //
    // Expecting calls:
    //  wire.begin()
    //  wire.beginTransmission(0x38)
    //  wire.endTransmission() -> 0
    //  time.pause(40)
    //  wire.requestFrom(0x38, 0x01)
    //  wire.available() -> 1
    //  wire.read() -> 0b00003000  Device calibrated.
    MockTime time;
    MockWire wire;

    EXPECT_CALL(wire, begin());
    EXPECT_CALL(wire, beginTransmission(0x38));
    EXPECT_CALL(wire, endTransmission()).WillOnce(Return(0));
    EXPECT_CALL(wire, requestFrom(0x38, 0x01));
    EXPECT_CALL(wire, available()).WillOnce(Return(1));
    EXPECT_CALL(wire, read()).WillOnce(Return(StatusCalibrated));
    EXPECT_CALL(time, pause(40));

    auto aht21 = AHT21WrapperArduino(time, wire);
    auto result = aht21.init();
    ASSERT_EQ(0, result);
}

TEST(AHT21WrapperArduino, InitNotConnected) {
    // If the device refuses to connect, the init method returns 1.
    //
    // Expecting calls:
    //  wire.begin()
    //  wire.beginTransmission(0x38)
    //  wire.endTransmission() -> 1
    //  wire.beginTransmission(0x38)
    //  wire.endTransmission() -> 1
    MockTime time;
    MockWire wire;

    EXPECT_CALL(wire, begin());
    EXPECT_CALL(wire, beginTransmission(0x38)).Times(2);
    EXPECT_CALL(wire, endTransmission()).Times(2).WillRepeatedly(Return(1));
    EXPECT_CALL(time, pause(20));

    auto aht21 = AHT21WrapperArduino(time, wire);
    auto result = aht21.init();
    ASSERT_EQ(1, result);
}

TEST(AHT21WrapperArduino, InitConnectionSecondChance) {
    // One should give a second chance when the first connection fails.
    //
    // Expecting calls:
    //  wire.begin()
    //  wire.beginTransmission(0x38)
    //  wire.endTransmission() -> 1
    //  time.pause(20)
    //  wire.beginTransmission(0x38)
    //  wire.endTransmission() -> 0
    //  time.pause(40)
    //  wire.requestFrom(0x38, 0x01)
    //  wire.available() -> 1
    //  wire.read() -> 0b00003000  Device calibrated.
    MockTime time;
    MockWire wire;

    EXPECT_CALL(wire, begin());
    EXPECT_CALL(wire, beginTransmission(0x38)).Times(2);
    EXPECT_CALL(wire, endTransmission())
        .Times(2)
        .WillOnce(Return(1))
        .WillOnce(Return(0));
    EXPECT_CALL(wire, requestFrom(0x38, 0x01));
    EXPECT_CALL(wire, available()).WillOnce(Return(1));
    EXPECT_CALL(wire, read()).WillOnce(Return(StatusCalibrated));
    EXPECT_CALL(time, pause(20));
    EXPECT_CALL(time, pause(40));

    auto aht21 = AHT21WrapperArduino(time, wire);
    auto result = aht21.init();
    ASSERT_EQ(0, result);
}

TEST(AHT21WrapperArduino, InitCalibrate) {
    // The device should be calibrated, if needed.
    //
    // Expecting calls:
    //  wire.begin()
    //  wire.beginTransmission(0x38)
    //  wire.endTransmission() -> 0
    //  time.pause(40)
    //  wire.requestFrom(0x38, 0x01)
    //  wire.available() -> 1
    //  wire.read() -> 0b00000000  Device not calibrated.
    //  wire.beginTransmission(0x38)
    //  wire.write(0xBE)
    //  wire.write(0x80)
    //  wire.write(0x00)
    //  wire.endTransmission() -> 0
    //  wire.beginTransmission(0x38)
    //  wire.write(0xAC)
    //  wire.write(0x30)
    //  wire.write(0x00)
    //  wire.endTransmission() -> 0
    //  time.pause(75)
    //  wire.available() -> 1
    //  wire.read() -> 0b00001000  Device not busy.
    //  wire.available() -> 1
    //  wire.read() -> 0b00001000  Device calibrated.
    MockTime time;
    MockWire wire;

    EXPECT_CALL(wire, begin());
    EXPECT_CALL(wire, beginTransmission(0x38)).Times(3);
    EXPECT_CALL(wire, endTransmission()).Times(3).WillRepeatedly(Return(0));
    EXPECT_CALL(wire, requestFrom(0x38, 0x01)).Times(3);
    EXPECT_CALL(wire, available()).Times(3).WillRepeatedly(Return(1));
    EXPECT_CALL(wire, read()).Times(3)
        .WillOnce(Return(0))  // Device not calibrated.
        .WillOnce(Return(StatusCalibrated))  // Device not busy.
        .WillOnce(Return(StatusCalibrated));  // Device calibrated now.
    EXPECT_CALL(wire, write(0xBE));
    EXPECT_CALL(wire, write(0x80));
    EXPECT_CALL(wire, write(0xAC));
    EXPECT_CALL(wire, write(0x30));
    EXPECT_CALL(wire, write(0x00)).Times(2);
    EXPECT_CALL(time, pause(40));
    EXPECT_CALL(time, pause(75));

    auto aht21 = AHT21WrapperArduino(time, wire);
    auto result = aht21.init();
    ASSERT_EQ(0, result);
}

TEST(AHT21WrapperArduino, InitBusy) {
    // If the device is busy, the initialization fails.
    //
    // Expecting calls:
    //  wire.begin()
    //  wire.beginTransmission(0x38)
    //  wire.endTransmission() -> 0
    //  time.pause(40)
    //  wire.requestFrom(0x38, 0x01)
    //  wire.available() -> 1
    //  wire.read() -> 0b00000000  Device not calibrated.
    //  wire.beginTransmission(0x38)
    //  wire.write(0xBE)
    //  wire.write(0x80)
    //  wire.write(0x00)
    //  wire.endTransmission() -> 0
    //  wire.beginTransmission(0x38)
    //  wire.write(0xAC)
    //  wire.write(0x30)
    //  wire.write(0x00)
    //  wire.endTransmission() -> 0
    //  time.pause(75)
    //  wire.available() -> 1     ┓ 1
    //  wire.read() -> 0b10000000 ┃ Device busy.
    //  time.pause(1)             ┛
    //  wire.available() -> 1     ┓ 2
    //  wire.read() -> 0b10000000 ┃ Device busy.
    //  time.pause(1)             ┛
    //  ...                       ┓ n
    //  ...                       ┃
    MockTime time;
    MockWire wire;

    EXPECT_CALL(wire, begin());
    EXPECT_CALL(wire, beginTransmission(0x38)).Times(3);
    EXPECT_CALL(wire, endTransmission()).Times(3).WillRepeatedly(Return(0));
    EXPECT_CALL(wire, requestFrom(0x38, 0x01)).Times(103);
    EXPECT_CALL(wire, available()).Times(103).WillRepeatedly(Return(1));
    EXPECT_CALL(wire, read()).Times(103)
        .WillOnce(Return(0))  // Device not calibrated.
        .WillRepeatedly(Return(StatusBusy));
    EXPECT_CALL(wire, write(0xBE));
    EXPECT_CALL(wire, write(0x80));
    EXPECT_CALL(wire, write(0xAC));
    EXPECT_CALL(wire, write(0x30));
    EXPECT_CALL(wire, write(0x00)).Times(2);
    EXPECT_CALL(time, pause(40));
    EXPECT_CALL(time, pause(75));
    EXPECT_CALL(time, pause(1)).Times(102);

    auto aht21 = AHT21WrapperArduino(time, wire);
    auto result = aht21.init();
    ASSERT_EQ(2, result);
}

For the sake of completeness, here’s the source code under test. Note, however, that the question is not about this piece of code, but rather the test code above.

#include "AHT21WrapperArduino.h"

#ifdef DEBUG_TESTS
#include <iostream>
#include <bitset>
#endif

AHT21WrapperArduino::AHT21WrapperArduino(Time &time, WireWrapper &wire) :
    time { time },
    wire { wire } { }

int AHT21WrapperArduino::init() {
    #ifdef DEBUG_TESTS
    std::cout << "Started the initialization of the device." << std::endl;
    #endif
    this->wire.begin();
    if (!this->isConnected()) {
        return 1;
    }

    this->time.pause(40);

    if (!this->isCalibrated()) {
        #ifdef DEBUG_TESTS
        std::cerr << "The device is not calibrated yet." << std::endl;
        #endif
        this->initialize();
        this->measure();
        this->time.pause(75);
        uint8_t counter = 0;
        while (this->isBusy()) {
            this->time.pause(1);
            if (counter > 100) {
                return 2;  // Give up after 100 ms.
            }

            ++counter;
        }

        if (!this->isCalibrated()) {
            return 3;
        }
    }

    #ifdef DEBUG_TESTS
    std::cerr << "Initialization finished." << std::endl;
    #endif
    return 0;
}

int AHT21WrapperArduino::read(float* temperature, float* humidity) {
    if (!this->available()) {
        return 1;
    }

    this->measure();
    this->time.pause(75);
    uint8_t counter = 0;
    while (this->isBusy()) {
        this->time.pause(1);
        if (counter > 100) {
            return 2;  // Give up after 100 ms.
        }

        ++counter;
    }

    this->readData();

    *temperature = ((float)temperatureData / 1048576) * 200 - 50;
    *humidity = ((float)humidityData / 1048576) * 100;
    return 0;
}

bool AHT21WrapperArduino::isConnected() {
    #ifdef DEBUG_TESTS
    std::cerr << "Determining if the device is connected." << std::endl;
    #endif
    this->wire.beginTransmission(this->deviceAddress);
    if (this->wire.endTransmission() == 0) {
        #ifdef DEBUG_TESTS
        std::cerr << "The device is connected." << std::endl;
        #endif
        return true;
    }

    #ifdef DEBUG_TESTS
    std::cerr << "Giving the device a second chance." << std::endl;
    #endif
    // If IC failed to respond, give it 20ms more for Power On Startup.
    // See datasheet, page 7.
    this->time.pause(20);

    this->wire.beginTransmission(this->deviceAddress);
    return this->wire.endTransmission() == 0;
}

uint8_t AHT21WrapperArduino::getStatus() {
    this->wire.requestFrom(this->deviceAddress, (uint8_t)1);
    if (this->wire.available()) {
        auto status = this->wire.read();
        #ifdef DEBUG_TESTS
        auto statusBits = std::bitset<8>(status);
        std::cerr << "The status is 0b" << statusBits << "." << std::endl;
        #endif
        return status;
    }

    return 0;
}

bool AHT21WrapperArduino::isCalibrated() {
    #ifdef DEBUG_TESTS
    std::cerr << "Determining if the device is calibrated." << std::endl;
    #endif
    return this->getStatus() & (1 << 3);
}

bool AHT21WrapperArduino::isBusy() {
    #ifdef DEBUG_TESTS
    std::cerr << "Determining if the device is busy." << std::endl;
    #endif
    return this->getStatus() & (1 << 7);
}

bool AHT21WrapperArduino::initialize() {
    #ifdef DEBUG_TESTS
    std::cerr << "Initializing the device." << std::endl;
    #endif
    this->wire.beginTransmission(this->deviceAddress);
    this->wire.write(0xBE);  // Initialize.
    this->wire.write(0x80);
    this->wire.write(0x00);
    return this->wire.endTransmission() == 0;
}

bool AHT21WrapperArduino::measure() {
    this->wire.beginTransmission(this->deviceAddress);
    this->wire.write(0xAC);  // Measure.
    this->wire.write(0x30);
    this->wire.write(0x00);
    return this->wire.endTransmission() == 0;
}

bool AHT21WrapperArduino::available() {
    if (this->isBusy()) {
        return false;
    }

    this->readData();
    return true;
}

void AHT21WrapperArduino::readData() {
    if (this->wire.requestFrom(this->deviceAddress, (uint8_t)6) > 0) {
        this->wire.read();
        uint32_t incoming = 0;
        incoming |= (uint32_t)this->wire.read() << (8 * 2);
        incoming |= (uint32_t)this->wire.read() << (8 * 1);
        uint8_t midByte = this->wire.read();
        incoming |= midByte;

        this->humidityData = incoming >> 4;
        this->temperatureData = (uint32_t)midByte << (8 * 2);
        this->temperatureData |= (uint32_t)this->wire.read() << (8 * 1);
        this->temperatureData |= (uint32_t)this->wire.read() << (8 * 0);
        this->temperatureData = this->temperatureData & ~(0xFFF00000);
    } else {
        this->humidityData = 0;
        this->temperatureData = 0;
    }
}
```

equipment damage – Is a water-damaged micro SD card likely to be readable?

Flash memory like SD and Micro SD cards is very robust, and flocculants in the water aren’t likely to damage either the plastic housing of the card or the electronics. If the contact strips (often gold plated, on better quality memory cards) aren’t too corroded to make contact, it’s very likely that someone who really cares and is willing to expend a little effort will be able to just plug the card into a card reader and read out its contents.

Even if the card is physically broken, it’s almost certain that someone who has reason to want to can connect the actual chip(s) inside to a new connector and read the content.

equipment damage – Is a water-damaged micro SD card likely to be readable?

Flash memory like SD and Micro SD cards is very robust, and flocculants in the water aren’t likely to damage either the plastic housing of the card or the electronics. If the contact strips (often gold plated, on better quality memory cards) aren’t too corroded to make contact, it’s very likely that someone who really cares and is willing to expend a little effort will be able to just plug the card into a card reader and read out its contents.

Even if the card is physically broken, it’s almost certain that someone who has reason to want to can connect the actual chip(s) inside to a new connector and read the content.

hard drive – “Disk you attached not readable” – PMBR/MBR corrupted?

Background:

Purchased 2 12TB WD Gold drives about 2 years ago and have been using them in an external enclosure without problem.

After upgrading my Mac mini server to 11.4, the message “The disk you attached is not readable” was displayed for this one drive post-boot. All other attached drives are fine, including it’s twin 12TB drive. The message follows the bad drive to other Macs.

Both 12TB drives are encrypted and APFS. They’re simply used for storage, so they’ve never been partitioned or set up for booting.

Since I have a twin drive (note: not a RAID pair, just an identical physical drive), I’ve compared them side by side, and the main issue that I’ve found so far is that it appears that the PMBR in sector 0 has been corrupted somehow.

Here’s output from gpt for the bad drive:

New-iMac:~ user$ sudo gpt -vv -r show /dev/disk2
Password:
gpt show: /dev/disk2: mediasize=12000138625024; sectorsize=512; blocks=23437770752
gpt show: /dev/disk2: MBR not found at sector 0
gpt show: /dev/disk2: Pri GPT at sector 1
gpt show: /dev/disk2: Sec GPT at sector 23437770751
        start         size  index  contents
            0            1         
            1            1         Pri GPT header
            2           32         Pri GPT table
           34            6         
           40       409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
       409640  23437098928      2  GPT part - 7C3457EF-0000-11AA-AA11-00306543ECAC
  23437508568       262151         
  23437770719           32         Sec GPT table
  23437770751            1         Sec GPT header

The good, twin drive:

iMac:~ user$ sudo gpt -vv -r show /dev/disk5
Password:
gpt show: /dev/disk5: mediasize=12000138625024; sectorsize=512; blocks=23437770752
gpt show: /dev/disk5: PMBR at sector 0
gpt show: /dev/disk5: Pri GPT at sector 1
gpt show: /dev/disk5: Sec GPT at sector 23437770751
        start         size  index  contents
            0            1         PMBR
            1            1         Pri GPT header
            2           32         Pri GPT table
           34            6         
           40       409600      1  GPT part - C12A7328-F81F-11D2-BA4B-00A0C93EC93B
       409640  23437098928      2  GPT part - 7C3457EF-0000-11AA-AA11-00306543ECAC
  23437508568       262151         
  23437770719           32         Sec GPT table
  23437770751            1         Sec GPT header

When I look at sector 0 on the good drive, I see what appear to be good/reasonable values when using iBored (old time Mac disk too which can read disk sectors, and show values for MBR partition table).

iBored MBR output - good disk

When I look at sector 0 on the bad drive, it (sector 0 only) is zeroed out completely.

All of the remaining sectors appear to be present (some other corruption notwithstanding). That is, data exists where I would expect it to exist and zeros exist where I expect zeros to exist. You can see that besides sector 0, gpt generates the exact same output that the good disk does.

My intuition – which I freely admit could be completely wrong – is that I may be able to edit sector 0 on the bad drive to match the values found on the good drive and then be able to at least try to mount the drive at that point.

However, I haven’t done anything yet other than looking. TIA for any help!

encryption – MacBook Pro is Powered On but Locked. Is my VeraCrypt data Readable if Laptop Stolen?

Secenario

Consider the case of a MacBook Pro with FileVault active. The computer is on and I’m properly logged on.

I frequently need to access sensitive data located in text files on an encrypted volume. The encrypted volume is created when I mount a particular file that lives on the main hard disk. The encryption program that mounts the file and makes the data available as a volume is called VeraCrypt.

When I leave my computer for brief periods, I lock my screen (Ctrl-Cmd-Q) but the computer is still on.

Question

If someone were to break in and steal my computer and run off with it while it were in that state, would he be able to read the contents of my VeraCrypt volume?

Assumptions

Assume that none of the volume’s files are open at the time of the theft. But the volume is mounted. Assume system file sharing is turned off and firewall is turned on. Assume no one else knows my system password.

Assume that the thief doesn’t have NSA-level hacking expertise; He doesn’t even know what he’s looking for (e.g. the volume name or what it contains). He’s just a run-of-the-mill criminal who saw a crime of opportunity to grab a laptop, but he’s open to snagging any content of value on the computer itself if he can find any.

Analysis

One thing I could do is dismount the Veracrypt virtual drive every time I leave the computer alone. It’s protected with a strong password that no one could guess. But dismounting and remounting that drive forces me to shutdown and subsequently restart and reinitialize a number of other processes that are specific to the work I do. It takes some time. My preference would be to leave that drive mounted during the brief time I’m away, but only if the lock screen provides sufficient security to protect the data.

I did read Data security while MacBook is on lock screen but this focuses more on FileVault, which as I understand it, offers minimal protective value when the computer is powered on.

Instead, I’m more interested in preventing read-access of a VeraCrypt volume. I’m not concerned about the data being deleted, overwritten, or otherwise corrupted by a bad actor — just read. I don’t care about the hypothetical thief reading anything else on the system’s main hard drive; My question is strictly about the readability of the encrypted volume when the OS is locked.

javascript – Statements that are not readable

I am having something like this

if (source.length > 0) {
    if (
        source(0).mandatory === true &&
        this.allInputs.documentsType !== "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    } else if (
        source(0).mandatory === false &&
        this.allInputs.documentsType === "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    }
} else {
    if (
        target(0).mandatory === true &&
        this.allInputs.documentsType === "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    } else if (
        target(0).mandatory === false &&
        this.allInputs.documentsType !== "mandatory"
    ) {
        item.mandatory = !item.mandatory;
    }
}

All is workign OK, the problem I have I think this is not readable a lot, can some body help me this refactor, thanks