I have a question regarding Google's oauth.
I found this module on npmjs.com called "google-assistant" Which allows you to integrate your app with google assistant (eg: answer text queries)
This is the code I got:
const path = require('path');
const GoogleAssistant = require('google-assistant');
const config = {
auth: {
keyFilePath: path.resolve(__dirname, 'client_secret_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com.json'), // x is a place holder for my client_secret json file name
// where you want the tokens to be saved
// will create the directory if not already there
savedTokensPath: path.resolve(__dirname, 'tokens.json'),
},
// this param is optional, but all options will be shown
conversation: {
(rest of the code is just the default example from https://npmjs.com/package/google-assistant/ )
Everytime I try run the code (node test.js) I get
[AuthError: No access or refresh token found] And when i remove the tokens.js file, It posts a 'link' and i paste it into my browser and it says 'paste this into your app:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
But the question is, Where do i paste it? Thanks
Related
I have store this service account key (my-key.json) file in my downloads folder (ubuntu)
and then i run this command into my console
export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json"
according to
google cloud. Now i am running this code but it throws me error.
const language = require('#google-cloud/language');
const quickstart = async function () {
// Instantiates a client
const client = new language.LanguageServiceClient();
// The text to analyze
const text = 'Hello, world!';
const document = {
content: text,
type: 'PLAIN_TEXT',
};
// Detects the sentiment of the text
const [result] = await client.analyzeSentiment({document: document});
const sentiment = result.documentSentiment;
console.log(`Text: ${text}`);
console.log(`Sentiment score: ${sentiment.score}`);
console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
}
quickstart();
**ERORR** -
(node:13928) UnhandledPromiseRejectionWarning: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:154:19)
at processTicksAndRejections (internal/process/task_queues.js:94:5)
at async GoogleAuth.getClient (/home/hardy/Documents/personal/project/node_modules/google-auth-library/build/src/auth/googleauth.js:485:17)
at async GrpcClient._getCredentials (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:88:24)
at async GrpcClient.createStub (/home/hardy/Documents/personal/project/node_modules/google-gax/build/src/grpc.js:213:23)
If you are using node <file-name>.js to initialize your code, you should update the command to
GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" node <file-name>.js
This will make the GOOGLE_APPLICATION_CREDENTIALS available inside your node-environment.
However, as a long-term solution, I would suggest creating a .env file and storing the GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/my-key.json" in that file.
And then using the dotenv package at the beginning of your js file in the following manner:
require('dotenv').config();
You can also refer to https://stackoverflow.com/a/27090755/7743705 for understanding how to set environment variables in pacakge.json.
To be able to run using npm without setting credentials each time
"scripts": {
"start": "set GOOGLE_APPLICATION_CREDENTIALS=[PATH]/credentials.json&& nodemon server.js"
},
For further reason on how to use env you can visit How to set environment variables from within package.json? for more comprehensive answers.
I search a lot for this on the internet but I don't find any article related to it.
Like I have a folder called pages in the root of my project and below tree is files of it.
| 404.js
| auth.js
| index.js
| _app.js
| _error.js
\---app
index.js
next.js gives default behavior when someone opens project.local:3000 it will openindex.js and project.local:3000/app it will open app/index.js but I want that when someone open app.project.local:3000 it will open app/index.js.
My Hosts file
127.0.0.1 project.local
127.0.0.1 app.project.local
In short
I want to redirect pages/app folder to app.project.local or app.example.com in next.js
Most updated solution
I found the solution while exploring the documentation on redirects.
In your Next.js's root folder, create a vercel.json file and then insert your redirects as object inside redirects array like so:
{
"redirects": [
{ "source": "/blog", "destination": "https://blog.example.com" }
]
}
This will only work on production environment. It should work as intended.
I'm still a noobie in next.js (2nd day learning), but I was searching for subdomain support and I found three solutions on this Github issue: https://github.com/vercel/next.js/issues/5682
Using zones (still no idea how it works)
"Vercel will implement subdomain routing in the near future" (I don't expect to use Vercel in the near future)
(my preferred, but not yet tested) An example using custom servers in Next.js: https://github.com/dcangulo/nextjs-subdomain-example
For #3, see how it was implemented in the server.js file
With the new "middleware" feature of Next.js, you can rewrite it using a function instead of the rewrite object and keep the getStaticProps working.
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { getValidSubdomain } from '#/utils/subdomain';
// RegExp for public files
const PUBLIC_FILE = /\.(.*)$/; // Files
export async function middleware(req: NextRequest) {
// Clone the URL
const url = req.nextUrl.clone();
// Skip public files
if (PUBLIC_FILE.test(url.pathname) || url.pathname.includes('_next')) return;
const host = req.headers.get('host');
const subdomain = getValidSubdomain(host);
if (subdomain) {
// Subdomain available, rewriting
console.log(`>>> Rewriting: ${url.pathname} to /${subdomain}${url.pathname}`);
url.pathname = `/${subdomain}${url.pathname}`;
}
return NextResponse.rewrite(url);
}
You can take a look on nextjs docs about middleware and I've also wrote this medium article with some related content that might help.
NextJS now supports Locales: https://nextjs.org/docs/advanced-features/i18n-routing.
You can specify a locale in your config, e.g. admin and specify the URL like this:
// next.config.js
module.exports = {
i18n: {
// These are all the locales you want to support in
// your application
locales: ['en-US', 'admin', 'nl-NL'],
// This is the default locale you want to be used when visiting
// a non-locale prefixed path e.g. `/hello`
defaultLocale: 'en-US',
// This is a list of locale domains and the default locale they
// should handle (these are only required when setting up domain routing)
// Note: subdomains must be included in the domain value to be matched e.g. "fr.example.com".
domains: [
{
domain: 'example.com',
defaultLocale: 'en-US',
},
{
domain: 'example.nl',
defaultLocale: 'nl-NL',
},
{
domain: 'admin.example.com',
defaultLocale: 'admin',
// an optional http field can also be used to test
// locale domains locally with http instead of https
http: true,
},
],
},
}
I'm building and trying do deploying a packaged electron app. FOr the packaging i used
electron-packager
electron-installer-debian
electron-installer-dmg
electron-winstaller
and I'm facing a little issue where I have to store tha appa datas somewhere in my user computer.
I saw that the good practice is to use the the folder in the path that is returned by the electron method app.getPath('userData').
from the docs
It is The directory for storing the app's configuration files, which by default it is the appData directory appended with the app name.
%APPDATA% on Windows
$XDG_CONFIG_HOME or ~/.config on Linux
~/Library/Application Support on macOS
By my tests sometimes this folder is not created automatically when the app is installed and other times yes and I'm wondering if i should create it or not.
Right now i'm quitting the app if this folder isn't present in the pc with the following code
var DatasPath = app.getPath('userData')
if (!fs.existsSync(DatasPath)){
process.exit()
}
So the question is
should i create the DatasPath folder with fs.mkdirSync(DatasPath); when it is not present or it is 'bad practice to do so', and if I can create the folder i have to warning the user the i have just added that folder?
(Expanding my reply from a "comment" to an "answer")
i don't know if i'm supposed to create it or not so i automatically
make the app quit if there is not that folder
It seems you are taking "userData" too literally? It is not an actual "folder" named "userData – it is a path to where the operating system stores data for that application. Electron currently runs on 3 operating systems and each one does things differently. For our convenience, Electron hides those differences by creating the wrapper method app.getPath(name) so the same code will work on each OS.
Try this: put the line below in your main.js script:
console.log(app.getPath('userData'));
/Users/*********/Library/Application Support/MyCoolApp
(the "*********" will be your user account name.)
UPDATED:
Run the code below in main.js and then look in the folder specified by the "userData" path
const fs = require("fs");
const path = require('path');
var datasPath = app.getPath('userData')
var data = "I am the cheese"
var filePath = path.join(datasPath, "savedData.txt")
fs.writeFileSync(filePath, data)
At pathConfig.js
function getAppDataPath() {
switch (process.platform) {
case "darwin": {
return path.join(process.env.HOME, "Library", "Application Support", "myApp");
}
case "win32": {
return path.join(process.env.APPDATA, "myApp");
}
case "linux": {
return path.join(process.env.HOME, ".myApp");
}
default: {
console.log("Unsupported platform!");
process.exit(1);
}
}
}
const appPath = __dirname;
const appDataPath =
!process.env.NODE_ENV || process.env.NODE_ENV === "production"
? getAppDataPath() // Live Mode
: path.join(appPath, "AppData"); // Dev Mode
if (!fs.existsSync(appDataPath)) {
// If the AppData dir doesn't exist at expected Path. Then Create
// Maybe the case when the user runs the app first.
fs.mkdirSync(appDataPath);
}
In each operating system the appData folder has a different path and the perfect way of getting this path is by calling app.getPath('userData') in the main process.
But there is a package that can handle this for you, it stores data in a JSON file and update it in every change.
In my opinion this package is much better than handling everything by your self.
Read more :
https://www.npmjs.com/package/electron-data-holder
This was working a couple months ago without code changes inside of my websocket server, however using it today it seems that the Google speech to text api no longer allows authentication using access tokens.
This was my previously working method until I hit this error today
const client = new speech.SpeechClient({
access_token: ACCESS_TOKEN,
projectId: 'project-name'
});
That nets me the above error in the title.
I also tried switching to a service account (which I used in the past) by setting up the environment as follows
export GOOGLE_APPLICATION_CREDENTIALS="path-to-key.json"
I then run the client without the above code and instead run:
const client = new speech.SpeechClient();
and that nets me this beautiful error instead, even though the environment is set at this point with the project Id
Error: Unable to detect a Project Id in the current environment.
Any help in resolving this would be much appreciated!
I resolved the environment problem and subsequent error by doing the following:
const options = {
keyFilename: 'path-to-key.json',
projectId: 'project-name',
};
const client = new speech.SpeechClient(options);
I was able to follow the Official Quickstart and got it working by using Client Libraries with no issues. I will explain what I did right below.
From Cloud Speech-to-Text - Quickstart:
Create or select a project:
gcloud config set project YOUR_PROJECT_NAME
Enable the Cloud Speech-to-Text API for the current project:
gcloud services enable speech.googleapis.com
Create a service account:
gcloud iam service-accounts create [SA-NAME] \
--description "[SA-DESCRIPTION]" \
--display-name "[SA-DISPLAY-NAME]"
Download a private key as JSON:
gcloud iam service-accounts keys create ~/key.json \
--iam-account [SA-NAME]#[PROJECT-ID].iam.gserviceaccount.com
Set the environment variable GOOGLE_APPLICATION_CREDENTIALS to the file path of the JSON file that contains your service account key:
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"
Install the Client Library
npm install --save #google-cloud/speech
Created a quickstart.js file and put the following code sample inside:
'use strict';
// [START speech_quickstart]
async function main() {
// Imports the Google Cloud client library
const speech = require('#google-cloud/speech');
const fs = require('fs');
// Creates a client
const client = new speech.SpeechClient();
// The name of the audio file to transcribe
const fileName = './resources/audio.raw';
// Reads a local audio file and converts it to base64
const file = fs.readFileSync(fileName);
const audioBytes = file.toString('base64');
// The audio file's encoding, sample rate in hertz, and BCP-47 language code
const audio = {
content: audioBytes,
};
const config = {
encoding: 'LINEAR16',
sampleRateHertz: 16000,
languageCode: 'en-US',
};
const request = {
audio: audio,
config: config,
};
// Detects speech in the audio file
const [response] = await client.recognize(request);
const transcription = response.results
.map(result => result.alternatives[0].transcript)
.join('\n');
console.log("Transcription: ${transcription}");
}
main().catch(console.error);
WHERE const fileName = './resources/audio.raw' is the path where your test.raw audio is located.
It works fine outside of node. I cant get it to work in node.js. Please help as this is my last resort. Ill need to see i suppose the correct layout of app.js
ITs something simple i knwo. No answers out there currently. I hope stack can
help.
Thanks. Mike
html file:
Weather
Get Weather Conditions From Anywhere!
Enter a location:
Get Current Humidity!
JS FILE:
$(document).ready(function() {
$('#weatherLocation').click(function() {
let city = $('#location').val();
$('#location').val("");
$.ajax({
url: `http://api.openweathermap.org/data/2.5/weather?q=${city}&appid=b7a0ab9fa0acf51a850b7a621c63d38f`,
type: 'GET',
data: {
format: 'json'
},
success: function(response) {
$('.showHumidity').text(`The humidity in ${city} is ${response.main.humidity}%`);
$('.showTemp').text(`The temperature in Kelvins is ${response.main.temp}.`);
},
error: function() {
$('#errors').text("There was an error processing your request. Please try again.");
}
});
});
});
APP.JS FILE
// app.js
var express = require('express');
var app = express();
var request = require('request');
app.use(express.static("app")); // Allow access to content of views folder (Showing how we get app to recognise folders)
// Allow access to content of views folder (Showing how we get app to recognise folders)
// Allow access to content of views folder (Showing how we get app to recognise folders)
app.use(express.static("js"));
app.use(express.static("views")); // Allow access to content of views folder (Showing how we get app to recognise folders)
app.use(express.static("images")); // Allow access to images folder (Showing how we get app to recognise folders)
// Allow access to content of views folder (Showing how we get app to recognise folders)
// Allow access to scripts folder {No need for this)
app.use(express.static("css")); // Allow access to css folder (Showing how we get app to recognise folders)
// Allow access to js folder (Showing how we get app to recognise
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Your app listening at https://%s:%s', host, port);
});
Node.js doesn't support HTML, or any kind of DOM*. Use console.log calls to output to stdout instead.
*by default.