channel in trivial GAE app not getting 'onmessage' - google-app-engine

I am trying to create the smallest possible GAE app to show the use of the channel api.
I have two handlers in the python, the first "TestPage" sends out the html shown below. The second "SendPage" tries to send a message over the channel to the test page. The code for the TestPage is
class TestPage(Handler):
def get(self):
token = channel.create_channel("1")
self.render("test.html", token = token)
It just creates the channel with an id of "1" and reders the page with the token passed back from create_channel().
The SendPage is just:
class SendPage(Handler):
def get(self):
channel.send_message("1", "hello")
self.write("sent hello to 1")
The html is as small as I could get it:
<!DOCTYPE HTML>
<html>
<body>
<br>Token is {{ token }}
<br>
<div id="debug">_</div>
<!--
<script src="https://talkgadget.google.com/talkgadget/channel.js"></script>
-->
<script src="static/channel.js"></script>
<script defer="defer">
function debug(s) {
document.getElementById("debug").innerHTML = s;
}
var channel = new goog.appengine.Channel( {{ token }} );
var socket = channel.open();
socket.onopen = function(e) {
debug("open");
}
socket.onclose = function(e) {
debug("close");
}
socket.onerror = function(e) {
debug("error");
}
socket.onmessage = function(e) {
debug("message");
}
debug("ready");
</script>
</body>
</html>
So, inside chrome I pull up TestPage and I see the "ready" message. Then I pull up the SendPage in another tab. And see the "sent message". Then when I go back to the TestPage I would expect to have "ready" replaced by "message". But this never happens. None of the socket handler functions are being called.
I'm stuck for the moment and would appreciate any help or suggestions.
Thank you.

Ok, I figured it out. There were two problems. First, the template line
var channel = new goog.appengine.Channel( {{ token }} );
should have been
var channel = new goog.appengine.Channel( "{{token}}" );
as it was token was something like "channel-2052893164-1373347311-1" which quietly evaluated to a number.
Second, the correct script for the channel.js was
<script type="text/javascript" src="/_ah/channel/jsapi"></script>
The other scripts I had referenced were from other stack overflow answers and I guess they did not properly apply to this problem.
Thanks.

Related

Call Solana web3.js from HTML

I am trying to run web3.js from HTML. Now so far I have been able to call window.solana.connect(); and window.solana.disconnect(); functions. However when I try run below code it doesn't work. I have tested it various options, like removing "web3." from the code but still didn't work. I would apprecaite if someone can guide me on how I can establish the connection.
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
Majority of my codes below is from the research done on Stackoveflow. Links below:
Solana : Adding Sollet / Phantom Wallet Connect to my website - Steps?
I would like to mint a new token on solana. How can I do this using solana-web3.js?
How can you transfer SOL using the web3.js sdk for Solana?
How to properly transfer Solana SOL using web3js via Phantom
Unfortunately docs on Phantom website don't help either. https://docs.phantom.app/integrating/establishing-a-connection
My existing codes below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to Decentralized Ecommerce</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/web3/3.0.0-rc.5/web3.min.js" integrity="sha512-jRzb6jM5wynT5UHyMW2+SD+yLsYPEU5uftImpzOcVTdu1J7VsynVmiuFTsitsoL5PJVQi+OtWbrpWq/I+kkF4Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="{{ url_for('static', filename='app.js') }}"></script>
<script src="https://unpkg.com/#solana/web3.js#latest/lib/index.iife.js"></script>
<script src="/static/solana.js"></script>
<script type="text/javascript">
async function transferSOL() {
//Changes are only here, in the beginning
if (window.solana.isConnected === false){
const resp = await window.solana.connect();
}
const pubKey = await window.solana.publicKey;
console.log("Public Key: ", pubKey);
// Establishing connection
const connection = new web3.Connection(web3.clusterApiUrl("devnet"));
alert('hello2');
// I have hardcoded my secondary wallet address here. You can take this address either from user input or your DB or wherever
var recieverWallet = new web3.PublicKey("4iSD5Q6AnyhRHu6Uz4u1KAzXh3TwNwwQshEGhZbEXUTw");
alert('hello3');
// Airdrop some SOL to the sender's wallet, so that it can handle the txn fee
var airdropSignature = await connection.requestAirdrop(
provider.publicKey,
web3.LAMPORTS_PER_SOL,
);
// Confirming that the airdrop went through
await connection.confirmTransaction(airdropSignature);
console.log("Airdropped");
var transaction = new web3.Transaction().add(
web3.SystemProgram.transfer({
fromPubkey: provider.publicKey,
toPubkey: recieverWallet,
lamports: web3.LAMPORTS_PER_SOL //Investing 1 SOL. Remember 1 Lamport = 10^-9 SOL.
}),
);
// Setting the variables for the transaction
transaction.feePayer = await provider.publicKey;
let blockhashObj = await connection.getRecentBlockhash();
transaction.recentBlockhash = await blockhashObj.blockhash;
// Transaction constructor initialized successfully
if(transaction) {
console.log("Txn created successfully");
}
// Request creator to sign the transaction (allow the transaction)
let signed = await provider.signTransaction(transaction);
// The signature is generated
let signature = await connection.sendRawTransaction(signed.serialize());
// Confirm whether the transaction went through or not
await connection.confirmTransaction(signature);
//Signature or the txn hash
console.log("Signature: ", signature);
}
</script>
</head>
After importing the script on the HTML:
<script src="https://unpkg.com/#solana/web3.js#latest/lib/index.iife.js"> </script>
You should be able to call:
const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl("mainnet-beta"));
Note it is solanaWeb3 not web3
Here is an example with Solana Web3 1.4:
import { Connection, clusterApiUrl } from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("devnet"), "confirmed");
Make sure to have installed the library via, npm install #solana/web3.js.

Media.net ads integration with SPA(angularjs)

How to integrate media.net ads in SPA(angularjs) website. I have copied and posted the given code in my website but it is not working(http://test.website.paperboy.com/).
<script id="mNCC" language="javascript">
medianet_width = "728";
medianet_height = "90";
medianet_crid = "xyz";
medianet_versionId = "xyz";
</script>
<script src="//contextual.media.net/nmedianet.js?cid=xyz"></script>
But it is working for non angular static site(https://test.website.paperboy.com/mobile-view.html).
I cannot speak for angularjs, but Angular 2 and beyond scrubs out script tags. Here is the solution for Angular 8. Note this is for the asynchronous ad code, not the synchronous code posted, but the methodology should be the same in which we are adding a DOM element:
.ts file:
convertToScript() {
var element = this.script.nativeElement;
var script = document.createElement('script');
script.id = 'mNCC';
script.lang = this.language ? this.language : 'javascript';
script.type = this.type ? this.type : 'text/javascript';
script.innerHTML = `
try {
window._mNHandle.queue.push(function (){
window._mNDetails.loadTag(${this.advertisement});
});
}
catch (error) {}`;
script['data-cfasync'] = 'false';
const parent = element.parentElement;
parent.parentElement.replaceChild(script, parent);
}
ngAfterViewInit() {
this.convertToScript();
}
.html file:
<div #script style.display="none">
<ng-content></ng-content>
</div>
Add the component where you want (inject the advertisement size and id here)
<div id="616415456">
<app-media-net-ad [type]="'text/javascript'" [advertisement]="advertisement">
</app-media-net-ad>
</div>
The advertisement variable should be formated as "ad_id,ad_size,ad_id". The header code can be added into the header section of your index.html file.

How to get a tensor from an image

I have an image and I would like to get the tensor from it.
Some of the images are already on the frontend server be whereas others will be served by the server
To do that, one needs to use fromPixels
In case the image is already displayed in an html page
You can consider doing a querySelector to get the image first and then you can use fromPixels
html
<img id="my-image" src="mydata.jpg">
js
const image = document.querySelector("#my-image")
const t = tf.fromPixels(image)
If the image is not present in the html page, you can use the constructor Image to create it and then pass it as parameter to fromPixels
const im = new Image()
im.onload = () => {
const a = tf.fromPixels(im, 4)
a.print()
console.log(a.shape)
}
im.src = "url-of-the-image"
document.body.appendChild(im)
onload makes sure that the image has finished downloading before converting it to a tensor.
If the image url and the url on which the frontend page is served are different there will be a cross-origin issue when creating the tensor. If the server serves the image with an access control that allows the frontend to retrieve that image, then setting the crossOrigin attribute of the image will solve the issue, otherwise there will nothing that can be done to get the tensor from that image.
const im = new Image()
im.crossOrigin = "anonymous";
im.src = "https://i.imgur.com/lVlPvCB.gif"
document.body.appendChild(im)
im.onload = () => {
const a = tf.fromPixels(im, 4)
a.print()
console.log(a.shape)
}
<html>
<head>
<!-- Load TensorFlow.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tensorflow/0.12.4/tf.js"> </script>
</head>
<body>
</body>
</html>

emails from gmail but response is gmail.readonly

I am trying to get the emails from gmail using https://www.googleapis.com/auth/gmail.readonly/?access_token='fdrt654vfdgfe6545But in response I am getting gmail.readonlyBut the System.HttpResponse[Status=OK, StatusCode=200] is fine. Can any guide me is there anything I am missing out.
This I how I requested got auth but in the response I received access token
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
</script>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
var AuthStates = {google: null};
function signinCallback(authResult) {
if (authResult['status']['signed_in']) {
// Update the app to reflect a signed in user
// Hide the sign-in button now that the user is authorized, for example:
document.getElementById('signinButton').setAttribute('style', 'display: none');
//alert(authResult['code']);
console.log('code state: ' + authResult['code']);
//console.log('authResult : ' + authResult[]);
AuthStates.google = authResult;
console.log('authResult 1 : ' + authResult['status']['method']);
console.log('auth Result : ' + authResult['id_token']);
//{!access_token} = authResult['access_token'];
//{!code} = authResult['code'];
connection(authResult['access_token'], authResult['code']);
} else {
// Update the app to reflect a signed out user
// Possible error values:
// "user_signed_out" - User is signed-out
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('Sign-in state: ' + authResult['error']);
}
}
</script>
<apex:outputPanel >
<span id="signinButton">
<span
class="g-signin"
data-callback="signinCallback"
data-clientid="clientid"
data-cookiepolicy="single_host_origin"
data-scope="https://www.googleapis.com/auth/gmail.readonly"
data-response_type="code"
data-redirect_uri="http://test-on.ap1.visual.force.com/apex/Gmail_inbox">
</span>
</span>
<apex:form >
So as i got my access token from my request I can go directly for getting all information related to the logedin user. As I am getting all the information regarding the user I am trying to get all the emails related to him. Is I am doing right or I am wrong any place. I am very new with api and web service trying to learn. please do help me put out.
You're actually making an HTTP GET call to that URL ( https://www.googleapis.com/auth/gmail.readonly/?access_token= ...)? Isn't that just the auth scope identifier?
Once you have a valid Oauth2 token you can set in the Auth header then you can make HTTP requests to the API. For example, to list messages see:
https://developers.google.com/gmail/api/v1/reference/users/messages/list
That has the URL to access (GET https://www.googleapis.com/gmail/v1/users/me/messages ) then once you have the message IDs you can get the messages individually following: https://developers.google.com/gmail/api/v1/reference/users/messages/get (e.g. GET https://www.googleapis.com/gmail/v1/users/me/messages/ ).
Usually there are good client libraries for the Google APIs. Not sure if that works for you, but see, for example:
https://developers.google.com/gmail/api/downloads

AngularJS & Flask : Passing data to html

I am trying to send the data from Flask to AngularJS.
Server
#app.route("/data")
def getDataFromDB():
cur.execute("select * from employee")
rows = cur.fetchall()
columns = [desc[0] for desc in cur.description]
result = []
for row in rows:
row = dict(zip(columns, row))
json_row=json.dumps(row)
result.append(json_row)
json_response=json.dumps(result)
response=Response(json_response,content_type='application/json; charset=utf-8')
response.headers.add('content-length',len(json_response))
response.status_code=200
return response
Client
maincontroller.js
var app=angular.module('myApp',[]);
app.controller("MainController", function($scope,$http){
var done=function(resp){
$scope.lists=resp.data;
};
var fail=function(err){
};
$http.get('http://10.62.XX.XX:8083/data')
.then(done,fail);
});
index.html
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"
type="text/javascript"></script>
<script src="app.js" type="text/javascript"></script>
<script src="maincontroller.js" type="text/javascript"></script>
</head>
<body ng-app="myApp">
<div id='content' ng-controller='MainController'>
<div>
<ul>
<li ng-repeat='ele in list'>{{ele}}</li>
</ul>
</div>
</div>
</body>
</html>
Now, when I access the above code using jsbin.com, I can see my api getting called but nothing is visible on the output screen in jsbin. It is blank.
But when I put the same code in eclipse, I see no api call happening. Do I need to do something more to make angularJS work? I just open the index.html with web browser.
If the IP is not your local machine you need to setup CORS on the server. I am not familiar with Flask but it looks like there is a package that handles this. I also found a function that sets up CORS for Flask.
from datetime import timedelta
from flask import Flask, make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True):
if methods is not None:
methods = ', '.join(sorted(x.upper() for x in methods))
if headers is not None and not isinstance(headers, basestring):
headers = ', '.join(x.upper() for x in headers)
if not isinstance(origin, basestring):
origin = ', '.join(origin)
if isinstance(max_age, timedelta):
max_age = max_age.total_seconds()
def get_methods():
if methods is not None:
return methods
options_resp = current_app.make_default_options_response()
return options_resp.headers['allow']
def decorator(f):
def wrapped_function(*args, **kwargs):
if automatic_options and request.method == 'OPTIONS':
resp = current_app.make_default_options_response()
else:
resp = make_response(f(*args, **kwargs))
if not attach_to_all and request.method != 'OPTIONS':
return resp
h = resp.headers
h['Access-Control-Allow-Origin'] = origin
h['Access-Control-Allow-Methods'] = get_methods()
h['Access-Control-Max-Age'] = str(max_age)
if headers is not None:
h['Access-Control-Allow-Headers'] = headers
return resp
f.provide_automatic_options = False
return update_wrapper(wrapped_function, f)
return decorator
#app.route('/')
#crossdomain(origin='*')
def landing():
return jsonify(i_am_a='cross domain resource!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080)

Resources