how to get md5checksum in search (google drtive api) - google-drive-api

I'm using drive v3 of google drive api, and I want google files name, id, mimeType and md5Checksum.
/** serarch files from google
* #param query
* #returns {Promise} with the result of the search
*
*/
async search(query, token) {
const config = {
headers: {
Authorization: `Bearer ${token}`,
},
params: {
q: `name contains '${query}' and trashed=false and mimeType != 'application/vnd.google-apps.shortcut' and mimeType != 'application/vnd.google-apps.folder'`,
fields: '*',
spaces: 'drive',
pageSize: 13,
},
};
if(query.length === 0 || !token) return [];
const result = [];
try {
const response = await axios.get(
`https://www.googleapis.com/drive/v3/files`,
config
);
const files = await response.data.files;
if (files.length) {
files.map(file => {
let googleObject = {};
googleObject.id = file.id;
googleObject.name = file.name;
googleObject.icon = file.iconLink;
googleObject.mimeType = file.mimeType;
googleObject.md5Checksum = file.md5Checksum;
result.push(googleObject);
});
} else {
result.push({
id: '',
name: 'No results',
icon: 'my-icon',
mimeType: '',
});
}
return JSON.stringify(result);
} catch (error) {
console.log('error ', error);
return null;
}
}
So i get a response from the server, something like this :
{
"id": "****",
"name": "test"
"icon": "https://drive-thirdparty.googleusercontent.com/16/type/application/vnd.google-apps.spreadsheet",
"mimeType": "application/vnd.google-apps.spreadsheet"
}
I can't figure out what I'm doing wrong, I try to replace
fields: 'files(id,name,mimeType,iconLink,md5Checksum)',
with
fields: '',* but i still have the same error (only id, name, mimetype and icon)

Related

NodeJS Send an email using pinpoint template with variables

I'm using #aws-sdk/client-pinpoint to send an email to a verified user.
async sendEmail(body: any): Promise<void> {
const fromAddress = 'test#domain.com';
const toAddress = 'test#domain.com';
const projectId = 'XXX-XXXX-XXXX';
const subject = 'Amazon Pinpoint Test (AWS SDK for JavaScript in Node.js)';
const body_text = `Amazon Pinpoint Test (SDK for JavaScript in Node.js)`;
const charset = 'UTF-8';
const params = {
ApplicationId: projectId,
MessageRequest: {
Addresses: {
[toAddress]: {
ChannelType: 'EMAIL',
},
},
MessageConfiguration: {
EmailMessage: {
FromAddress: fromAddress,
SimpleEmail: {
Subject: {
Charset: charset,
Data: subject,
},
HtmlPart: {
Charset: charset,
Data: 'body_html',
},
TextPart: {
Charset: charset,
Data: body_text,
},
},
},
},
},
};
try {
const data = await this.pinpointClient.send(new SendMessagesCommand(params));
const { MessageResponse } = data;
if (!MessageResponse || !MessageResponse.Result) throw Error('Failed!');
const recipientResult = MessageResponse?.Result[toAddress];
if (recipientResult.StatusCode !== 200) {
throw new Error(recipientResult.StatusMessage);
} else {
console.log(recipientResult.MessageId);
}
} catch (err) {
console.log(err.message);
}
}
And everything is working fine. But when I try to use a pre-defined template, it is not being send for some reason and no errors were shown as well! I'm lost on how to pass template Name/ARN with substitution. Any idea on how to achieve that?
Cheers!
use Template Configuration in message configuration
TemplateConfiguration: {
EmailTemplate: {
'Name': 'template name',
'Version': 'latest'
}
}
async sendEmail(body: any): Promise<void> {
const fromAddress = 'test#domain.com';
const toAddress = 'test#domain.com';
const projectId = 'XXX-XXXX-XXXX';
const subject = 'Amazon Pinpoint Test (AWS SDK for JavaScript in Node.js)';
const body_text = `Amazon Pinpoint Test (SDK for JavaScript in Node.js)`;
const charset = 'UTF-8';
const params = {
ApplicationId: projectId,
MessageRequest: {
Addresses: {
[toAddress]: {
ChannelType: 'EMAIL',
},
},
MessageConfiguration: {
EmailMessage: {
FromAddress: fromAddress,
SimpleEmail: {
Subject: {
Charset: charset,
Data: subject,
},
HtmlPart: {
Charset: charset,
Data: 'body_html',
},
TextPart: {
Charset: charset,
Data: body_text,
},
},
},
},
TemplateConfiguration: {
EmailTemplate: {
'Name': 'template name',
'Version': 'latest'
}
}
},
};
try {
const data = await this.pinpointClient.send(new SendMessagesCommand(params));
const { MessageResponse } = data;
if (!MessageResponse || !MessageResponse.Result) throw Error('Failed!');
const recipientResult = MessageResponse?.Result[toAddress];
if (recipientResult.StatusCode !== 200) {
throw new Error(recipientResult.StatusMessage);
} else {
console.log(recipientResult.MessageId);
}
} catch (err) {
console.log(err.message);
}
}

update column to record if an app script is run for that row or not in google sheets

I am trying to run a google app script with Whatsapp business API to send messages to my customers directly from google sheets. The below app runs fine but every time I run it, it sends the message again and again to all customers irrespective of the same msg being sent to the same customer earlier.
Is there a way, I can add a column and update it automatically to record if the message has been sent to this customer in which case skip to the next (just like in mail merge scripts).
I have the below code and a screenshot of the image here
const WHATSAPP_ACCESS_TOKEN = "**My whatsapp token**";
const WHATSAPP_TEMPLATE_NAME = "**My template name**";
const LANGUAGE_CODE = "en";
const sendMessage_ = ({
recipient_number,
customer_name,
item_name,
delivery_date,
}) => {
const apiUrl = "**My api url**";
const request = UrlFetchApp.fetch(apiUrl, {
muteHttpExceptions: true,
method: "POST",
headers: {
Authorization: `Bearer ${WHATSAPP_ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
payload: JSON.stringify({
messaging_product: "whatsapp",
type: "template",
to: recipient_number,
template: {
name: WHATSAPP_TEMPLATE_NAME,
language: { code: LANGUAGE_CODE },
components: [
{
type: "body",
parameters: [
{
type: "text",
text: customer_name,
},
{
type: "text",
text: item_name,
},
{
type: "text",
text: delivery_date,
},
],
},
],
},
}),
});
const { error } = JSON.parse(request);
const status = error ? `Error: ${JSON.stringify(error)}` : `Message sent to ${recipient_number}`;
Logger.log(status);
};
const getSheetData_ = () => {
const [header, ...rows] = SpreadsheetApp.getActiveSheet().getDataRange().getDisplayValues();
const data = [];
rows.forEach((row) => {
const recipient = { };
header.forEach((title, column) => {
recipient[title] = row[column];
});
data.push(recipient);
});
return data;
};
const main = () => {
const data = getSheetData_();
data.forEach((recipient) => {
const status = sendMessage_({
recipient_number: recipient["Phone Number"].replace(/[^\d]/g, ""),
customer_name: recipient["Customer Name"],
item_name: recipient["Item Name"],
delivery_date: recipient["Delivery Date"],
});
});
};
In your situation, how about modifying your script as follows? Please modify main as follows.
From:
const data = getSheetData_();
To:
const temp = getSheetData_();
const { data, ranges } = temp.reduce((o, e, i) => {
if (e["Sent"] != "sent") {
o.data.push(e);
o.ranges.push(`E${i + 2}`);
}
return o;
}, { data: [], ranges: [] });
if (ranges.length > 0) {
SpreadsheetApp.getActiveSheet().getRangeList(ranges).setValue("sent");
}
By this modification, this script checks the column "E" of "Sent". And, the row values without "sent" in column "E" are retrieved as data. And, the value of "sent" is put into column "E" of the retrieved rows.
Reference:
reduce()

Web3js BatchRequest Balances from List of Tokens Fails on execute()

This is my batch.js file which contains the relevant code. I am importing some variables from other files but I've isolated the problem to this file:
const Web3 = require('web3')
const fs = require('fs')
const { convertToNumber, getTokens } = require('./utils')
const { abi, bathEndpoint, walletAddress, blockNumber } = require('./constant.js')
const web3 = new Web3(new Web3.providers.HttpProvider(bathEndpoint))
const generateContractFunctionList = ({ tokens, blockNumber }) => {
const batch = new web3.BatchRequest()
tokens.map(async ({ address: tokenAddress, symbol, decimals }) => {
// console.log('tokenAddress :>> ', tokenAddress)
if (tokenAddress != null && tokenAddress != '') {
const contract = new web3.eth.Contract(abi)
contract.options.address = tokenAddress
try {
batch.add(
contract.methods
.balanceOf(walletAddress)
.call.request({}, blockNumber)
)
} catch (error) {
console.error('Error adding request to batch for token ', tokenAddress)
}
}
})
return batch
}
const main = async () => {
//const { tokens } = await getTokens()
const tokens = JSON.parse(fs.readFileSync('./tokenArrayFormatted1.json'));
console.log('tokens retrieved :>> ', tokens.length)
// const batch = generateContractFunctionList({ tokens })
// query block number
const batch = generateContractFunctionList({ tokens, blockNumber: blockNumber })
const tokenBalances = {}
const tokensIgnored = []
let batchData
try {
batchData = await batch.execute()
} catch (error) {
console.error('Error retrieving balances for some tokens')
batchData = error
}
try {
batchData.response.forEach((res, index) => {
const { name, decimals, symbol } = tokens[index]
if (res && res._hex) {
tokenBalances[name] = `${convertToNumber(res._hex, decimals)} ${symbol}`
} else {
tokensIgnored.push(name)
}
})
} catch (error) {
console.error('Error retrieving balances for some tokens')
batchData = error
}
console.log(
'The following tokens returned an error when checking balance:',
tokensIgnored
)
console.log('----------')
console.log(
`Balance checked for ${Object.keys(tokenBalances).length} tokens:`
)
console.log(tokenBalances)
}
main()
tokenArrayFormatted1.json looks like this:
[
{
"chainId": 1,
"address": "0xf3AE5d769e153Ef72b4e3591aC004E89F48107a1",
"name": "Deeper Network",
"symbol": "DPR",
"decimals": 18
},
{
"chainId": 1,
"address": "0xf680429328caaaCabee69b7A9FdB21a71419c063",
"name": "Butterfly Protocol Governance Token",
"symbol": "BFLY",
"decimals": 18
}
]
When I run node batch.js I keep getting an error telling me that batchData.response is undefined when the code tries to do a forEach over it. I logged batch to the console and it looked like this.
Batch {
requestManager: RequestManager {
provider: HttpProvider {
withCredentials: false,
timeout: 0,
headers: undefined,
agent: undefined,
connected: false,
host: 'https://USERNAME:PASSWORD#BASEURLOFGETHNODE.com',
httpsAgent: [Agent]
},
providers: {
WebsocketProvider: [Function: WebsocketProvider],
HttpProvider: [Function: HttpProvider],
IpcProvider: [Function: IpcProvider]
},
subscriptions: Map(0) {}
},
requests: [
{
params: [Array],
callback: undefined,
method: 'eth_call',
format: [Function: bound ]
},
{
params: [Array],
callback: undefined,
method: 'eth_call',
format: [Function: bound ]
}
]
}
Where USERNAME,PASSWORD, and BASEURLOFGETHNODE refer to my actual credentials.
And then batchData which is created by the line let batchData = await batch.execute() is undefined when logged to the console. So clearly await batch.execute() is producing nothing. I am using Chainstack Geth node API's (with an archive node) and web3js as indicated above. What seems to be the problem?
let batchData = await batch.execute()
batch.execute() does not return a promise if you read the source code, in fact it sends the JSON RPC batch request and call each request callback individually, so what you need to do is turn the execute function into asynchronous one returning an array of responses, and this is how to do it :
const Jsonrpc = require('web3-core-requestmanager/src/jsonrpc');
var { errors } = require('web3-core-helpers');
function executeAsync(batch) {
return new Promise((resolve, reject) => {
var requests = batch.requests;
batch.requestManager.sendBatch(requests, (err, results) => {
results = results || [];
var response = requests.map((request, index) => {
return results[index] || {};
}).map((result, index) => {
if (result && result.error) {
return errors.ErrorResponse(result);
}
if (!Jsonrpc.isValidResponse(result)) {
return errors.InvalidResponse(result);
}
return requests[index].format ? requests[index].format(result.result) : result.result;
});
resolve(response);
});
})
}
To use this function :
(async () => {
var batch = new web3.BatchRequest();
batch.add(web3.eth.getBlock.request("latest"));
var batchResponse = await executeAsync(batch);
console.log(batchResponse);
})()

'fetch' from router - how to have 'res.status(400).json('Enter failure message here')' be handled as an error in .then .catch?

I have the following code as part of a Button in one of my React Native components. Observe how there is no .catch to handle a possible 'no results' case from server; it is handled with if-statements instead (e.g.: else if (acceptMatchRequestData['status']==='failure') which I was what I'm trying to get away from.
await acceptMatchRequest(match['matchId'], userId, getUserInfoData[0]['ratings'][matchType])
.then(acceptMatchRequestData => {
if (acceptMatchRequestData['status']==='success') {
setMatchInvites(prevState => {
return prevState.filter((observation, i) => observation['matchId'] !== match['matchId'])
})
setMatchScreenParentState('loading')
sendToUserDeviceNotification('matchFound', userId, match['matchedUserId'])
} else if (acceptMatchRequestData['status']==='failure') {
Alert.alert('', acceptMatchRequestData['message'])
}
})
acceptMatchRequest function code:
export async function acceptMatchRequest(matchId, userId, rating) {
console.log('Attempting to accept match request');
info = { matchId, userId, rating }
const firebaseIdToken = await AsyncStorage.getItem('#firebaseIdToken')
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + firebaseIdToken },
body: JSON.stringify(info)
};
const response = await fetch(ngrokOrLocalhost + '/acceptmatchrequest', requestOptions)
const data = await response.json()
return data
}
And server code:
router.post('/acceptmatchrequest', async (req, res) => {
const { matchId, userId, rating } = req.body;
const results = await Match.find({ 'usersInfo.userId': userId, 'matchRecords.matchConfirmed': { $nin: [true] } }).limit(5)
if (results.length===5) {
res.status(400).json({'status': 'failure', 'message': 'You already have 5 active matches. Please finish a match first before you can accept this match.'})
} else {
var filter2 = { '_id': matchId }
var update2 = { 'isCustomRequest_IsAccepted': true, '$push': { 'usersInfo': { 'userId': userId, 'location': { 'type': 'Point', 'coordinates': [0, 0] }, 'rating': rating } } }
var response2 = await Match.findOneAndUpdate(filter2, update2, { new: true, sort: { 'matchCreatedTimestamp': 1 } })
if (response2) {
// Document was updated
res.status(200).json({'status': 'success', 'message': 'Match request was accepted successfully'})
} else {
console.log('Match request was not accepted successfully');
res.status(400).json({'status': 'failure', 'message': 'Match request was not accepted successfully'})
}
}
})

Upload Excel file and download from mysql using Node js

I want to upload Excel sheet and after submit that excel sheet need to insert data into mysql database and same sheet which we upload need to download.
I have tried below code:
Node Service-
function getDetails(req, res) {
var sampleFile, fileInfo = {};
var post = req.body;
var ID= post.id;
var name=post.name
if (!req.files) {
res.send('No files were uploaded.');
return;
}
sampleFile = req.files.fileInputXLSX;
console.log("req.body -- ",req.body);
console.log("Uploaded -- ",sampleFile);
// Get file attributes
var fileId = req.body.fileId;
var fileExtn = sampleFile.name.split(".").pop();
var extractedFilename = sampleFile.name.slice(0, sampleFile.name.lastIndexOf('.'));
var uploadFileName = extractedFilename+'_'+fileId+'.'+fileExtn;
console.log("uploadFileName -- ",uploadFileName);
fileInfo = {
"name": uploadFileName,
"mimetype": sampleFile.mimetype
}
sampleFile.mv(__dirname+'/Myuploads/Details/'+uploadFileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
// Update file info
var queryString = "INSERT INTO 'details'('id','name') VALUES ('" + ID + "','" + name + "')";
connection.query(queryString, function(err, result) {
if (!err){
var response = [];
response.push({'result' : 'success'});
if (result.length != 0) {
response.push({'data' : result});
} else {
response.push({'msg' : 'No Result Found'});
}
res.setHeader('Content-Type', 'application/json');
res.status(200).send(JSON.stringify(response));
} else {
res.status(400).send(err);
}
});
}
});
}
Controller.js
$scope.MyFunction=function(){
var excelForm = new FormData();
excelForm.append('fileInputXLSX', document.getElementById("fileInputXLSX").files[0]);
console.log("---- excelFile : ", document.getElementById("fileInputXLSX").files[0]);
// End : Get File
$http.post(Data.baseNodeService + "getDetails", {
"newProtocolObj": $scope.newProtocolObj
},headconfig).success(function(data, status, headers, config) {
console.log('Details: success');
excelForm.append('fileId', data);
jQuery.ajax({
url: data.baseNodeService + "getDetails",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: excelForm,
success: function(data) {
console.log("---- upload response : ", data);
$scope.goToTfilePage();
}
});
// End : Upload File
}).error(function(map_data, status, headers, config) {
console.log('Details: error');
console.log('status: ', status, '\nmap_data: ', map_data, '\nconfig: ', config);
});
}
Message is coming in console: No file is uploaded.
Please help with the same.It is not upload the file.It is not able to read the response from node service.
I am new in this help in which manner i need to write.
Edit:I am able to upload the file but how to insert into mysql database??