how to use strophe with XMPP or Pujab - xmpp

I have successfully installed following items as i want to Integrate Facebook Chat Into my web page
Python
Punjab
Twisted
on my windows XP , but now i want to use strophe library , to connect with Punjab.
Does anyone know how do i use strophe library , as i tried one example listed below supplied in
strophe library. The problem is i don't know what to specify in JID and Password field which is being asked by basic.html page.
Note:
as punjab is successfully installed on my windows xp and i am getting XEP-0124 - BOSH response too
Environment is localhost
basic.js
var BOSH_SERVICE = 'http://bosh.metajack.im:5280/xmpp-httpbind'
var connection = null;
function log(msg)
{
$('#log').append('<div></div>').append(document.createTextNode(msg));
}
function rawInput(data)
{
log('RECV: ' + data);
}
function rawOutput(data)
{
log('SENT: ' + data);
}
function onConnect(status)
{
if (status == Strophe.Status.CONNECTING) {
log('Strophe is connecting.');
} else if (status == Strophe.Status.CONNFAIL) {
log('Strophe failed to connect.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.DISCONNECTING) {
log('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
log('Strophe is disconnected.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.CONNECTED) {
log('Strophe is connected.');
connection.disconnect();
}
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.rawInput = rawInput;
connection.rawOutput = rawOutput;
$('#connect').bind('click', function () {
var button = $('#connect').get(0);
if (button.value == 'connect') {
button.value = 'disconnect';
connection.connect($('#jid').get(0).value,
$('#pass').get(0).value,
onConnect);
} else {
button.value = 'connect';
connection.disconnect();
}
});
});
basic.html
<!DOCTYPE html>
<html>
<head>
<title>Strophe.js Basic Example</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'></script>
<script src='../strophe.js'></script>
<script src='basic.js'></script>
</head>
<body>
<div id='login' style='text-align: center'>
<form name='cred'>
<label for='jid'>JID:</label>
<input type='text' id='jid'>
<label for='pass'>Password:</label>
<input type='password' id='pass'>
<input type='button' id='connect' value='connect'>
</form>
</div>
<hr>
<div id='log'></div>
</body>
</html>

I have create an account over here and get JID and Password for free
and for localhost , use JID as 'localhost' only and you can leave password blank.

Related

Module not found: Can't resolve 'dns' Error on NextJS Page

Im new to NextJS and try to implement a symple Login Page. When the user types in valid credentials than he gets redirected to another page, else he gets an error. I use an MongoDB Database to check with the credentials the user provided. I followed a Video from the MongoDB YouTube Channel and ChatGPT helped as well but now I`m stuck with the error that a module was not found: Module not found: Can't resolve 'dns'.
Has somebody an idea what Im doing wrong?
This is my Login Page, the functions get called when the user submits the form.
`
import Head from "next/head"
import styles from "../styles/Login.module.scss"
import { connectToDatabase } from '../util/mongodb';
export default function Login() {
async function checkCredentials(username, password) {
try {
//Connect to Database
const { db } = await connectToDatabase()
//get Data from Collection userdata
const collection = db.collection('userdata');
// Find the user with the specified username and password
const user = await collection.findOne({ username, password });
if (user) {
// User was found, credentials are valid
console.log('Valid credentials');
return true;
} else {
// User was not found, credentials are invalid
console.log('Invalid credentials');
return false;
}
} catch (error) {
console.error(error);
}
finally {
db.close();
}
}
function handleSubmit(event) {
event.preventDefault();
const username = event.target.elements.username.value;
const password = event.target.elements.password.value;
checkCredentials(username, password).then((result) => {
if (result) {
// Credentials are valid, log the user in
// ...
console.log("Login succesfull")
} else {
// Credentials are invalid, show an error message
// ...
console.log("Login not successfull")
}
});
}
return (
<div>
<Head>
<title>Login</title>
</Head>
<main className={styles.login}>
<section>
<img src="/images/Bild_SD.jpg" alt="Beispielbild Squaredance" />
</section>
<section>
<h1>Login</h1>
<p>Hier kannst du dich einloggen, um auf Interne Informationen zugreifen zu koennen. </p>
<form onSubmit={handleSubmit}>
<label htmlFor="username">Benutzername:</label>
<input type="text" id="username" name="username" />
<br />
<label htmlFor="password">Passwort:</label>
<input type="password" id="password" name="password" />
<br />
<button type="submit">Anmelden</button>
</form>
</section>
</main>
</div>
)
}
And here is the mongodb.js file, where I connect with the database. The code here is entirely from a YouTube Video from the official MongoDB Channel and I use it on another Page, so there should be nothing wrong there.
import { MongoClient } from "mongodb";
const { MONGODB_URI, MONGODB_DB } = process.env
if (!MONGODB_URI) {
throw new Error(
'Bitte bestimme die MONGODB_URI Variable in .env.local'
)
}
if (!MONGODB_DB) {
throw new Error(
'Bitte bestimme die MONGODB_DB Variable in .env.local'
)
}
/**
* Globall is used here to maintain a chached connection across hot reloads
* in development. This prevents connections growing exponentially
* during api Route usage.
*/
let cached = global.mongo
if (!cached) {
cached = global.mongo = { conn: null, promise: null }
}
export async function connectToDatabase() {
if (cached.conn) {
return cached.conn
}
if (!cached.promise) {
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
cached.promise = MongoClient.connect(MONGODB_URI, opts).then((client) => {
return {
client,
db: client.db(MONGODB_DB),
}
})
cached.conn = await cached.promise
return cached.conn
}
}
`
I looked a bit for myself and found out the error occurs probably because I connect to the Database in Frontend. I have a folder called api inside the pages folder. Should I put the checkCredentials function in a file there? Is the function then in the backend? How could this look like?
It would be great if somebody could help!

Receive 'subscribe' presences with Strophe.js Roster plugin and Ejabberd

I'm using the Strophe.js Roster plugin with Ejabberd as XMPP Server. When I use Adium or some other XMPP Clients I can add some other accounts in my Roster. When I send an invitation, the other account receives presence with type=='subscribe'.
Wit Strophe.js Roster, I never receive any presence with type == 'subscribe'!
I tried everything...I added some handlers...I "filtered" and ...
Here is my code :
HTML includes
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'></script>
<script src='../strophe.js'></script>
<script src="../strophe.muc.js"></script>
<script src="../strophe.register.js"></script>
<script src="../strophe.roster.js"></script>
<script src='my-code.js'></script>
my-code.js
var jid;
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE, {'keepalive': true});
//connection.rawInput = rawInput;
//connection.rawOutput = rawOutput;
connection.addHandler(onPresence, null, 'presence', null, null, null);
connection.roster.registerRequestCallback(onRequest);
// Manage connection
try {
$('#connect').get(0).value = 'disconnect';
connection.restore(null, onRegister);
} catch(e) {
if (e.name !== "StropheSessionError") { throw(e); }
$('#connect').get(0).value = 'connect';
}
$('#connect').bind('click', function () {
var button = $('#connect').get(0);
if (button.value == 'connect') {
button.value = 'disconnect';
jid = $('#jid').get(0).value;
connection.connect(jid, $('#pass').get(0).value, onConnect, 10);
} else {
button.value = 'connect';
connection.disconnect();
}
});
});
function onPresence(stanza)
{
log("PRESENCE");
console.log(stanza);
return true;
}
function onRequest(req) {
console.log("Request");
console.log(req);
return true;
}
Am I missing something?
I solved my problem!
We must send a presence when the connection's status is
Strophe.Status.CONNECTING
function onConnect(status)
{
if (status == Strophe.Status.CONNECTING) {
log('Strophe is connecting.');
} else if (status == Strophe.Status.CONNFAIL) {
log('Strophe failed to connect.');
} else if (status == Strophe.Status.DISCONNECTING) {
log('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
log('Strophe is disconnected.');
} else if (status == Strophe.Status.CONNECTED) {
log('Strophe is connected.');
// Send a presence to the server
connection.send($pres().tree());
}
}

Pass polymer form data to rest api

I'm looking for some way to pass data from a Polymer form fields to REST API,
actually, I'm using core-ajax to do it but I think is a bit heavy method to do it.
Are any standard way to do it?
This is my code:
<template>
<section>
<file-input class="blue" id="file" extensions='[ "xls" ]' maxFiles="1">{{ FileInputLabel }}</file-input>
</section>
<section>
<paper-button raised class="blue" disabled?="{{ (! Validated) || (Submitted) }}" on-tap="{{ Submit }}">
<core-icon icon="send"></core-icon>
Process
</paper-button>
</section>
<paper-toast id="toast" text=""></paper-toast>
<core-ajax id="ajax" url="/import-pdi" method="POST" handleAs="json" response="{{ response }}" on-core-complete="{{ SubmitFinished }}"></core-ajax>
</template>
<script>
Polymer("import-pdi-form", {
Validated: false,
Submitted: false,
FileInputLabel: "SELECT",
ready: function () {
this.shadowRoot.querySelector("#file").addEventListener("change", function(event) {
var container = document.querySelector("import-pdi-form");
container.Validated = (event.detail.valid.length != 0);
if (event.detail.valid.length == 0) {
container.shadowRoot.querySelector("#toast").text = "Invalid Format";
container.shadowRoot.querySelector("#toast").show();
container.FileInputLabel = "SELECCIONA L'ARXIU";
}
else {
container.FileInputLabel = event.detail.valid[0].name;
var form_data = new FormData();
form_data.append("file", event.detail.valid[0], event.detail.valid[0].name);
container.shadowRoot.querySelector("#ajax").body = form_data;
container.shadowRoot.querySelector("#ajax").contentType = null;
}
});
},
Submit: function() {
if ((this.Validated) && (! this.Submitted)) {
this.Submitted = true;
this.shadowRoot.querySelector("#ajax").go();
}
},
SubmitFinished: function(event, detail, sender) {
if (detail.xhr.status == 200) {
this.shadowRoot.querySelector("#toast").text = JSON.parse(detail.xhr.response).message;
}
else {
this.shadowRoot.querySelector("#toast").text = "Server Error";
}
this.shadowRoot.querySelector("#toast").show();
this.FileInputLabel = "SELECCIONA L'ARXIU";
this.shadowRoot.querySelector("#file").reset();
this.Submitted = false;
}
});
</script>
For submitting a form that contains custom elements we currently recommend that you use the ajax-form element. It looks like you may already be using the file-input element by the same author, so the two should work well together.

Error loading MacroEngine script (file: LawyerProfileView.cshtml)

Working on site i been handed and suddnely a couple of macros have started playing up. Macro was working fine now suddenly this error showed up can anyone help here is the code.
#using umbraco.MacroEngines
#inherits umbraco.MacroEngines.DynamicNodeContext
#functions{
public void SetPageTitle(string title)
{
var page = HttpContext.Current.Handler as Page;
if (page != null){
page.Title = title;
}
}
public DynamicNode Homepage
{
get {
var homepage = Model;
while(homepage.NodeTypeAlias != "Homepage"){
homepage = homepage.Parent;
}
return homepage;
}
}
public HtmlString GetSocialMediaLink(string network, string url, string name)
{
var socialMediaRepo = Library.NodeById(-1).DescendantsOrSelf("SocialMediaNetworkRepository").First();
var socialNetworks = new List<DynamicNode>();
if (socialMediaRepo != null)
{
foreach (var child in socialMediaRepo.Children)
{
if(child.NodeTypeAlias.ToLower().Equals(network.ToLower())){
var icon = child.HasValue("CssClass") ? String.Format("<i class=\"{0}\"></i>", child.CssClass) : String.Format("<img src=\"/imagegen.ashx?altimage=/images/assets/clear.gif&image={0}\" alt=\"{1}\"/>", child.Icon, child.Name);
return new HtmlString(String.Format("<a target=\"_blank\" rel=\"no-follow\" href=\"{0}\" title=\"{3} on {1}\">{2}</a>", url, child.Name, icon, name) );
}
socialNetworks.Add(child);
}
}
return new HtmlString("");
}
}
#{
if (String.IsNullOrEmpty(Request["name"])){
return;
}
var profileId = Request["name"].Replace("-", " ").Replace("/", "");
var lawyersRepository = Library.NodeById(1316);
var isIntranet = Homepage.Name.IndexOf("intranet", StringComparison.OrdinalIgnoreCase) > -1;
var nodes = isIntranet ? lawyersRepository.Children.Where("Name.ToLower() = \"" + profileId.ToLower() + "\"") : lawyersRepository.Children.Where("!ProfileIsPrivate && Name.ToLower() = \"" + profileId.ToLower() + "\"");
if(!nodes.Any()){
return;
}
var node = nodes.First();
if (node == null || node.NodeTypeAlias != "LawyerRepositoryItem"){
return;
}
if (node.ProfileIsPrivate && !isIntranet){
return;
}
PageData["PageTitle"] = Model.Name + " - " + node.Name;
SetPageTitle(Model.Name + " - " + node.Name);
var hasContactInfo = (!String.IsNullOrEmpty(node.TelephoneNumber) || !String.IsNullOrEmpty(node.EmailAddress) || !String.IsNullOrEmpty(node.OfficeLocation));
<div class="profile">
<div class="row">
<div class="span4 profile-content">
<h1>#node.Name</h1>
<h3>#node.JobTitle</h3>
#Html.Raw(node.Biography.ToString())
</div>
<div class="span2">
<div class="profile-picture">
#{
if (!node.HasValue("ProfilePictureSquare")){
<img src="/imagegen.ashx?altimage=/images/assets/clear.gif&image=#Library.MediaById(node.ProfilePicture).umbracoFile" alt="#node.Name" />
}
else{
<img src="/imagegen.ashx?altimage=/images/assets/clear.gif&image=#Library.MediaById(node.ProfilePictureSquare).umbracoFile" alt="#node.Name" />
}
}
</div>
<div class="profile-quote">
<!--Tesimonial-->
#RenderPage("~/macroScripts/Widgets/Widget_RandomTestimonial.cshtml", #node.Id.ToString())
</div>
</div>
#if (hasContactInfo)
{
<div class="contact-information">
<div class="pull-left contact-details">
<h4>#Dictionary.ContactInformationHeading</h4>
<dl class="">
#{
if (node.HasValue("TelephoneNumber"))
{
<dd><strong>#Dictionary.Label_TelephoneShort:</strong> #node.TelephoneNumber</dd>
}
if (node.HasValue("EmailAddress"))
{
<dd><strong>#Dictionary.Label_EmailShort:</strong> #node.EmailAddress</dd>
}
if (node.HasValue("OfficeLocation"))
{
var officeNode = Library.NodeById(node.OfficeLocation);
<dd><strong>#Dictionary.Label_Office:</strong> #officeNode.Name</dd>
}
}
</dl>
</div>
<div class="pull-left contact-vcard">
<h4>
<i class="t-icon-vcard"></i> <span>#Dictionary.DownloadVCard</span></h4>
</div>
</div>
}
#{
var hasSocialMediaUrls = node.HasValue("FacebookUrl") || node.HasValue("TwitterUrl") || node.HasValue("LinkedInUrl") || node.HasValue("YouTubeUrl") || node.HasValue("BlogUrl");
if (hasSocialMediaUrls)
{
<div class="profile-social-links social-links">
<ul class="unstyled">
<li><strong>#Dictionary.Connect</strong></li>
#if (node.HasValue("FacebookUrl"))
{
<li>#GetSocialMediaLink("facebook", node.FacebookUrl, node.Name)</li>
}
#if (node.HasValue("TwitterUrl"))
{
<li>#GetSocialMediaLink("twitter", node.TwitterUrl, node.Name)</li>
}
#if (node.HasValue("LinkedInUrl"))
{
<li>#GetSocialMediaLink("linkedin", node.LinkedInUrl, node.Name)</li>
}
#if (node.HasValue("YouTubeUrl"))
{
<li>#GetSocialMediaLink("youtube", node.YouTubeUrl, node.Name)</li>
}
#if (node.HasValue("BlogUrl"))
{
<li>#GetSocialMediaLink("blogger", node.BlogUrl, node.Name)</li>
}
</ul>
</div>
}
}
</div>
<div class="gold-bar">
#Dictionary.SubmitTestimonialText
</div>
</div>
}
i have tried loading from a backup file but the problem persists.
You will need to find out why you got this error.
If you are running in a macro AND you are in WebForms mode, you can add ?umbDebugShowTrace=true (or ?umbDebug=true) at the url. (first check if the umbracoDebugMode appsetting in the web.config is true).
If this is not working, check the App_Data/Logs/ folder for any log files. You should see the complete error there. If you have an older version, check also the umbracoLog database table.
Best thing to do is to look in /App_Data/Logs/UmbracoTraceLog.txt which will show you the logs recorded for today.
This will reveal the root of the error and full stack trace.

Static html page created the WebSocket connection golang server directly

I'm writing an html page that needs to create a websocket to the server
On the server, I used the example in "code.google.com/p/go.net/websocket" just accept the connection.
However, in Chrome26 the response is
WebSocket connection to 'ws://127.0.0.1:1234/' failed: Unexpected response code: 400
Is there something is missed (like a handshake)?
This is my html and server is using go
<html>
<head></head>
<body>
<script type="text/javascript">
var sock = null;
var wsuri = "ws://127.0.0.1:1234";
window.onload = function() {
console.log("onload");
sock = new WebSocket(wsuri);
sock.onopen = function() {
console.log("connected to " + wsuri);
}
sock.onclose = function(e) {
console.log("connection closed (" + e.code + ")");
}
sock.onmessage = function(e) {
console.log("message received: " + e.data);
}
};
function send() {
var msg = document.getElementById('message').value;
sock.send(msg);
};
</script>
<h1>WebSocket Echo Test</h1>
<form>
<p>
Message: <input id="message" type="text" value="Hello, world!">
</p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>
//------------------------------
package main
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
)
func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("Can't receive")
break
}
fmt.Println("Received back from client: " + reply)
msg := "Received: " + reply
fmt.Println("Sending to client: " + msg)
if err = websocket.Message.Send(ws, msg); err != nil {
fmt.Println("Can't send")
break
}
}
}
func main() {
http.Handle("/", websocket.Handler(Echo))
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
Chrome is likely throwing error 400 because it thinks you are trying to do a cross-domain request to the websocket server and thinks it is unlikely you have permission.
To solve the issue you simply have to server your html from your go-server too.
So change your sock.go code to:
package main
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
)
func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("Can't receive")
break
}
fmt.Println("Received back from client: " + reply)
msg := "Received: " + reply
fmt.Println("Sending to client: " + msg)
if err = websocket.Message.Send(ws, msg); err != nil {
fmt.Println("Can't send")
break
}
}
}
func main() {
http.Handle("/", http.FileServer(http.Dir("."))) // <-- note this line
http.Handle("/socket", websocket.Handler(Echo))
log.Println("serving")
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
and add your index.html file to the same directory as your sock.go file:
<html>
<head></head>
<body>
<script type="text/javascript">
var sock = null;
var wsuri = "ws://127.0.0.1:1234/socket"; // <-- note new path
window.onload = function() {
console.log("onload");
sock = new WebSocket(wsuri);
sock.onopen = function() {
console.log("connected to " + wsuri);
}
sock.onclose = function(e) {
console.log("connection closed (" + e.code + ")");
}
sock.onmessage = function(e) {
console.log("message received: " + e.data);
}
};
function send() {
var msg = document.getElementById('message').value;
sock.send(msg);
};
</script>
<h1>WebSocket Echo Test</h1>
<form>
<p>
Message: <input id="message" type="text" value="Hello, world!">
</p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>
Now you will be able to connect from within chrome.