I am trying to get a cookie from the middleware of Nextjs 13 and I can't find up to date information on this.
My question: is there a way to see the cookie before rendering the html.
window is fined or something?
page.tsx
async function getData() {
const nextCookies = cookies(); // Get cookies object
try {
let cityToken = nextCookies.get('regionCode'); // Find cookie city
return cityToken;
} catch (e) {
console.log(e);
}
}
export default async function Page() {
const nextCookies = cookies(); // Get cookies object
const token = nextCookies.get('new'); // Find cookie for is new user
// const cityToken = await getData();
const cityToken = cookies().get('regionCode')?.value;
console.log(cityToken);
}
middleware.tsx
const myFunction = async () => {
// https://geolocation.onetrust.com/cookieconsentpub/v1/geo/location
// run asynchronous tasks here - ip location
const response = await fetch('https://www.cloudflare.com/cdn-cgi/trace');
const text = await response.text();
const arr = text.split('\n');
const ip = arr.filter((v) => v.includes('ip='))[0].split('=')[1];
// https://stackoverflow.com/questions/65752416/how-can-i-most-easily-parse-this-http-response-into-json-to-then-access-response
// https://stackoverflow.com/questions/64591296/access-to-fetch-at-https-www-cloudflare-com-cdn-cgi-trace-from-origin-http
const ipCity = await fetch(`https://ipapi.co/${ip}/json/`);
const textJson = await ipCity.json();
};
const data = await myFunction();
res.cookies.set('regionCode', 'textJson.region');
const IgApiClient = require('instagram-private-api').IgApiClient;
const fs = require('fs');
const config = require('./config.json');
const ig = new IgApiClient();
ig.state.generateDevice(config.instagramUsername);
ig.state.proxyUrl = config.igProxy;
async function uploadImage(imageBuffer) {
const imageUrl = await ig.upload.photo(
{
file: imageBuffer
}
);
console.log(`URL: ${imageUrl}`);
}
(async () => {
await ig.simulate.preLoginFlow();
const loggedInUser = await ig.account.login(config.instagramUsername, config.instagramPassword);
process.nextTick(async () => await ig.simulate.postLoginFlow());
const imageBuffer = fs.readFileSync('output.png');
uploadImage(imageBuffer);
})();
Error:
C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126
return new errors_1.IgResponseError(response);
^
IgResponseError: POST /rupload_igphoto/1672943340753_0_8268117741 - 400 Bad Request;
at Request.handleResponseError (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:126:16)
at Request.send (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\core\request.js:54:28)
at async UploadRepository.photo (C:\Users\PC\Desktop\spotted\node_modules\instagram-private-api\dist\repositories\upload.repository.js:18:26)
at async uploadImage (C:\Users\PC\Desktop\spotted\bomba.js:10:20)
Node.js v19.2.0
Hello, I've been trying to create an app, which will automatically post generated images on instagram, but there's a problem, it doesn't work even if i do it as it is intended in documentation (probably). Does anyone have any ideas?
I'm trying to implement a reminders dialogflow agent in node js that reminds the user on his google calendar upcoming events. however I'm getting an No responses defined for platform: null error when calling the intent for listing the upcoming events.
This is my code:
const express = require('express');
const google = require('googleapis').google;
const jwt = require('jsonwebtoken');
const dfff = require('dialogflow-fulfillment')
const {googlec} = require('googleapis');
// Google's OAuth2 client
const OAuth2 = google.auth.OAuth2;
// Including our config file
const CONFIG = require('./config');
// Creating our express application
const app = express();
// Allowing ourselves to use cookies
const cookieParser = require('cookie-parser');
app.use(cookieParser());
// Setting up EJS Views
app.set('view engine', 'ejs');
app.set('views', __dirname);
console.log(dfff)
app.get('/', function (req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(CONFIG.oauth2Credentials.client_id, CONFIG.oauth2Credentials.client_secret, CONFIG.oauth2Credentials.redirect_uris[0]);
// Obtain the google login link to which we'll send our users to give us access
const loginLink = oauth2Client.generateAuthUrl({
access_type: 'offline', // Indicates that we need to be able to access data continously without the user constantly giving us consent
scope: CONFIG.oauth2Credentials.scopes // Using the access scopes from our config file
});
return res.render("index", { loginLink: loginLink });
});
app.get('/auth_callback', function (req, res) {
// Create an OAuth2 client object from the credentials in our config file
const oauth2Client = new OAuth2(CONFIG.oauth2Credentials.client_id, CONFIG.oauth2Credentials.client_secret, CONFIG.oauth2Credentials.redirect_uris[0]);
if (req.query.error) {
// The user did not give us permission.
return res.redirect('/error');
} else {
oauth2Client.getToken(req.query.code, function(err, token) {
if (err)
return res.redirect('/');
// Store the credentials given by google into a jsonwebtoken in a cookie called 'jwt'
res.cookie('jwt', jwt.sign(token, CONFIG.JWTsecret));
return res.redirect('/');
});
}
});
app.post('/', express.json(),(req,res)=>{
//if (!req.cookies.jwt) {
// We haven't logged in
//return res.redirect('/');
//}
const oauth2Client = new OAuth2(CONFIG.oauth2Credentials.client_id, CONFIG.oauth2Credentials.client_secret, CONFIG.oauth2Credentials.redirect_uris[0]);
const calendar = google.calendar({version: 'v3' , auth:oauth2Client});
const agent = new dfff.WebhookClient({
request : req,
response : res
})
function welcome(agent){
agent.add("Hi")
}
function listEvents(agent){
calendar.events.list({
'calendarId': 'primary',
'auth':oauth2Client,
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'singleEvents': true,
'orderBy': 'startTime'
}).then((err,response)=> {
let events = response.result.items;
if (events.length > 0) {
for (let i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
return agent.add('Be ready for '+ event.summary + ' event '+ 'at ' + when )
}}
else {
return agent.add('You dont have any upcoming events.');
}
});
}
let intenMap = new Map()
intenMap.set('Default_Welcome_Intent',welcome)
intenMap.set('Remind_me',listEvents)
agent.handleRequest(intenMap)
});
// Listen on the port defined in the config file
app.listen(CONFIG.port, function () {
console.log(`Listening on port ${CONFIG.port}`);
});
Whenever listEvents function is processed I'm getting (Error: No responses defined for platform null) any idea why?
The issue is that listEvents() does an asynchronous operation that returns a Promise (the call to calendar.events.list()), which you handle through the .then() block, but you don't have a way for the agent.handleRequest() function to know this and to wait for the Promise to complete. To do this, you need to return a Promise.
Fortunately, in your case, the solution is straightforward, since the call and then() chain return a Promise, you can just return it. This would be done by adding the return keyword before calendar.events.list(). It might look something like this:
function listEvents(agent){
return calendar.events.list({
// Parameters go here
}).then((err,response)=> {
// Code to handle response and return a message go here
});
}
Given the protocol buffers definition available at: https://github.com/googleapis/googleapis/blob/master/google/home/graph/v1/homegraph.proto
How can one call the Home Graph API RPC endpoint using gRPC on Node.js to multiplex concurrent API method calls over a single connection?
You can use #grpc-js in combination with Application Default Credentials to initialize the credentials.
$ npm install #grpc/grpc-js
$ npm install google-auth-library
$ export GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account-key.json
const grpc = require('#grpc/grpc-js');
const { GoogleAuth } = require('google-auth-library');
async function getCredentials() {
const sslCredentials = grpc.credentials.createSsl();
const googleAuth = new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/homegraph'
});
const authClient = await googleAuth.getClient();
const callCredentials = grpc.credentials.createFromGoogleCredential(
authClient
);
const credentials = grpc.credentials.combineChannelCredentials(
sslCredentials,
callCredentials
);
return credentials;
}
Use google-proto-files with #grpc/proto-loader to load the Home Graph service protobuf definition with its dependencies.
const protoLoader = require('#grpc/proto-loader');
const protos = require('google-proto-files');
async function getHomegraph() {
const homegraphProto = await protoLoader.load(
protos.getProtoPath('home/graph', 'v1', 'homegraph.proto'), {
includeDirs: [protos.getProtoPath('..')]
}
);
const homegraph = grpc.loadPackageDefinition(
homegraphProto
).google.home.graph.v1;
return homegraph;
}
And finally initialize client stubs to call the HomeGraphApiService methods.
(async function() {
const credentials = await getCredentials();
const homegraph = await getHomegraph();
const homegraphService = new homegraph.HomeGraphApiService(
'homegraph.googleapis.com', credentials
);
homegraphService.sync({
agentUserId: 'AGENT_USER_ID'
}, function(err, result) {
if (err) {
console.error(err);
} else {
console.log(result);
}
});
// homegraphService.query();
// homegraphService.requestSyncDevices();
// homegraphService.reportStateAndNotification();
// homegraphService.deleteAgentUser();
})();
Note that by default the Channel implementation will reuse existing channels from a global pool if the parameters (address, credentials and options) are the same. You can alter this behavior with the grpc.use_local_subchannel_pool option.
I have a scenario, where I am trying to fetch the API responses of the following host url of my account spaces and orgs in cloudfoundry SAP.
https://api.cf.eu10.hana.ondemand.com
I am using nodejs (wrapper cf-client) script to authenticate but whenever I try to login it provides below error
Error: {"error":"unauthorized","error_description":"{"error":"invalid_grant","error_description":"User authentication failed: INVALID_AUTHORIZATION_HEADER_LENGTH"}"}
Here is my nodejs script
"use-strict";
const endpoint = "https://api.cf.eu10.hana.ondemand.com";
const username = "myusername"; //I have created a trial account
const password = "Password"; //I have created a trial account
const JsonFind = require('json-find');
const fs = require('fs')
const util = require('util');
const dJSON = require('dirty-json');
const CloudController = new (require("cf-client")).CloudController(endpoint);
const UsersUAA = new (require("cf-client")).UsersUAA;
const Apps = new (require("cf-client")).Apps(endpoint);
const Spaces = new (require("cf-client")).Spaces(endpoint);
const Orgs = new (require("cf-client")).Organizations(endpoint);
CloudController.getInfo().then( (result) => {
UsersUAA.setEndPoint(result.authorization_endpoint);
return UsersUAA.login(username, password);
}).then( (result) => {
Orgs.setToken(result);
return Orgs.getOrganizations();
}).then((result) => {
all_orgs = result.resources //returns api
get_orgs=util.inspect(all_orgs, {depth: null});
console.log(get_orgs)
});
What I have seen is when I normaly login with cf client it requires sso passcode along with username password.
how can i provide that here or any idea how can I login here and fetch the data.
Since I did little more research on this and found out that a token generator can be used to overcome this, below code.
"use-strict";
var totp = require('totp-generator');
const endpoint = "https://api.cf.eu10.hana.ondemand.com";
var token = totp('clientsecretidgoeshere');
const username = "myusername"; //I have created a trial account
const password = "Password"+token; //I have created a trial account
const JsonFind = require('json-find');
const fs = require('fs')
const util = require('util');
const dJSON = require('dirty-json');
const CloudController = new (require("cf-client")).CloudController(endpoint);
const UsersUAA = new (require("cf-client")).UsersUAA;
const Apps = new (require("cf-client")).Apps(endpoint);
const Spaces = new (require("cf-client")).Spaces(endpoint);
const Orgs = new (require("cf-client")).Organizations(endpoint);
CloudController.getInfo().then( (result) => {
UsersUAA.setEndPoint(result.authorization_endpoint);
return UsersUAA.login(username, password);
}).then( (result) => {
Orgs.setToken(result);
return Orgs.getOrganizations();
}).then((result) => {
all_orgs = result.resources //returns api
get_orgs=util.inspect(all_orgs, {depth: null});
console.log(get_orgs)
});