How to search registered user on ejabberd server from client side using smack library? - ejabberd

I am using smack on the client-side. I tried to search registered users on the client-side because before creating a new user I want to know that the id is registered on server or not if not then create the user either log in the user but ejabberd server crashed with the error. Here are the crash logs of ejabberd server.
Failed to process iq:
#iq{
id = <<"Hh6AJ-28">>,type = set,lang = <<"en">>,
from =
#jid{
user = <<"admin">>,server = <<"faiqkhan-virtualbox">>,
resource = <<"92526029764259513741138">>,luser = <<"admin">>,
lserver = <<"faiqkhan-virtualbox">>,
lresource = <<"92526029764259513741138">>},
to =
#jid{
user = <<>>,server = <<"vjud.faiqkhan-virtualbox">>,resource = <<>>,
luser = <<>>,lserver = <<"vjud.faiqkhan-virtualbox">>,lresource = <<>>},
sub_els =
[#xmlel{
name = <<"query">>,
attrs = [{<<"xmlns">>,<<"jabber:iq:search">>}],
children =
[#xmlel{
name = <<"x">>,
attrs = [{<<"xmlns">>,<<"jabber:x:data">>},{<<"type">>,<<"submit">>}],
children =
[#xmlel{
name = <<"field">>,
attrs = [{<<"var">>,<<"user">>},{<<"type">>,<<"text-single">>}],
children =
[#xmlel{
name = <<"value">>,attrs = [],
children = [{xmlcdata,<<"wasiq#faiqkhan-virtualbox">>}]}]}]}]}],
meta = #{ip => {0,0,0,0,0,65535,49320,11092}}}
exception error: {module_not_loaded,mod_vcard_mnesia,
<<"faiqkhan-virtualbox">>}
in function gen_mod:get_module_opts/2 (src/gen_mod.erl, line 338)
in call from gen_mod:get_module_opt/3 (src/gen_mod.erl, line 318)
in call from mod_vcard_mnesia:filter_fields/3 (src/mod_vcard_mnesia.erl, line 200)
in call from mod_vcard_mnesia:search/4 (src/mod_vcard_mnesia.erl, line 78)
in call from mod_vcard:search_result/4 (src/mod_vcard.erl, line 479)
in call from mod_vcard:process_search/1 (src/mod_vcard.erl, line 264)
in call from gen_iq_handler:process_iq/3 (src/gen_iq_handler.erl, line 131)
in call from gen_iq_handler:process_iq/4 (src/gen_iq_handler.erl, line 109)
I used the following code to get a registered user from the client-side:
InetAddress address = InetAddress.getByName(HOST);
DomainBareJid serviceName = JidCreate.domainBareFrom("faiqkhan-VirtualBox"); XMPPTCPConnectionConfiguration.Builder builder = XMPPTCPConnectionConfiguration.builder();
builder.setPort(PORT);
builder.setSendPresence(true);
builder.setHostAddress(address);
builder.setServiceName(serviceName);
builder.setUsernameAndPassword("admin", "123456");
builder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
XMPPTCPConnection connection = new XMPPTCPConnection(builder.build());
try {
connection.connect();
connection.login("admin", "123456");
Logger.showError("21560-connection created to: " + connection.getHost());
Roster roster = Roster.getInstanceFor(connection);
Set<RosterEntry> entities = roster.getEntries();
UserSearchManager search = new UserSearchManager(connection);
DomainBareJid s = JidCreate.domainBareFrom("vjud.".concat("faiqkhan-VirtualBox"));
Form searchForm = search.getSearchForm(s);
Form answerForm = searchForm.createAnswerForm();
answerForm.setAnswer("user", "wasiq#faiqkhan-virtualbox");
ReportedData data = search.getSearchResults(answerForm, s);
if (data.getRows() != null) {
for (ReportedData.Row row : data.getRows()) {
for (CharSequence value : row.getValues("jid")) {
Log.i("Iteartor values......", " " + value);
}
}
}
} catch (SmackException | IOException | XMPPException | InterruptedException e) {
Logger.showError("21560-error on account creation: " + e.getMessage());
}
Server crashed on ReportedData data = search.getSearchResults(answerForm, s); line of code.

You found a bug in ejabberd:
It was already fixed in 2018 in
https://github.com/processone/ejabberd/commit/1be21126342d503205798605725ba5ceef9de42b
but the bug got reintroduced in 2019 in
https://github.com/processone/ejabberd/commit/a02cff0e780bb735531594c4ece81e8628f79782#diff-71f613241ed580c3e5dad2b4526503f2R12
and I've now applied a temporary fix in
https://github.com/processone/ejabberd/commit/92913389a51ddc564f11e0712b0d82fca8c9aecb
But even if that bug is fixed, the feature you want to use probably doesn't help: a user must set his vCard in order for his account to be provided in vJud search. In other words, vJUD searches in stored vCards, not in registered accounts. If I register an account but don't set a vCard, then vJUD will not find it.
before creating a new user I want to know that the id is registered on server or not
And why don't you simply attempt to register the account first?
On the other hand, if you would like to check in advance if an account is available for registration or not (like some web registration sites do, to allow the user modify the username until one is available), then I think XMPP doesn't provide that possibility for security reasons: it is not allowed to know if an account exists or not.
A solution for that would be to use the check_account ejabberd command
https://docs.ejabberd.im/developer/ejabberd-api/admin-api/#check-account
executing it with some frontend, like ejabberdctl, ReST or XMLRPC
https://docs.ejabberd.im/admin/guide/managing/#ejabberd-commands
$ ejabberdctl check_account user1 localhost
$ ejabberdctl check_account user6666 localhost
Error: false
~ 1

Related

Getting PidLidEndRecurrenceDate value using Ews

What is the correct way of getting PidLidEndRecurrenceDate values using Ews. below code does not give proper result. property details that i am looking is https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxprops/816378cf-07ef-4926-b7d2-53475792403d
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("X#X.com", "XXX");
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ItemView view = new ItemView(10);
Guid MyPropertySetId = new Guid("{6ED8DA90-450B-101B-98DA-00AA003F1305}");
int intValue = Convert.ToInt32("0x0000000F", 16);
ExtendedPropertyDefinition extendedPropertyDefinition =
new ExtendedPropertyDefinition(MyPropertySetId, intValue, MapiPropertyType.Integer);
view.PropertySet =
new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, extendedPropertyDefinition);
FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Calendar, view);
foreach (Item item in findResults.Items)
{
Console.WriteLine(item.Subject);
if (item.ExtendedProperties.Count > 0)
{
// Display the extended name and value of the extended property.
foreach (ExtendedProperty extendedProperty in item.ExtendedProperties)
{
Console.WriteLine(" Extended Property Name: " + extendedProperty.PropertyDefinition.Name);
Console.WriteLine(" Extended Property Value: " + extendedProperty.Value);
}
}
}
That property is set on the Meeting invite messages only not on the Master instance of the Calendar Appointments which is what you seem to be looking at. For the Master instances you should just be able to use the strongly typed property https://learn.microsoft.com/en-us/dotnet/api/microsoft.exchange.webservices.data.recurrence.enddate?redirectedfrom=MSDN&view=exchange-ews-api#Microsoft_Exchange_WebServices_Data_Recurrence_EndDate
It you wanted to view the property you have above search the SentItems Folder for invites with recurrences (with Enddates) and that's where you will see it. Or probably easier just look at the messages with a Mapi editor like OutlookSpy or MFCMAPI and you will see the properties available.

Didn't get values from mysql when more than one data frame inserting in python

I am trying to read xlsx file from unread mail and convert it to data frame finally it will insert into MySQL DB.To avoid duplication while inserting each row of data frame i check if the data already present in db,for this duplication i check mails one by one.
My issue is when two or more unread mail is present in inbox this duplication check fails.
detach_dir = os.path.dirname(os.path.abspath(__file__)) +
'/attachments'
user = "abc#outlook.in"
pwd = "xyz#123*"
m = imaplib.IMAP4_SSL("outlook.office365.com")
m.login(user,pwd)
# Select the mailbox
m.select("folder name in mail")
n = 0
resp, items = m.search(None, '(UNSEEN)')
items = items[0].split()
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)")
email_body = data[0][1]
mail = email.message_from_bytes(email_body)
if mail.get_content_maintype() != 'multipart':
continue
att_path = os.path.join(detach_dir, filename)
if not os.path.isfile(att_path) :
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
df_mail = pd.read_excel(att_path,skiprows=
[0,2,3,4,5,6,7,8,9],skip_blank_lines=True,skipfooter=1,index=False)
df_mail = df_mail.fillna(0)
df_mail.dropna(how="all", inplace=True)
for i, row in df_mail.iterrows():
sql = 'SELECT * FROM `tablename WHERE condition for duplicate'
extist=con.execute(sql)
duplicate=extist.fetchall()
if len(duplicate) == 0:
df_mail.iloc[i:i+1].to_sql('table', con = engine, if_exists = 'append', chunksize = 1000,index=False)
else:
print("duplicate data")
Can you please share your code and a list of things you have tried? It is very hard to help without those.

I want to know why I cannot use this function?

yahoo<-function(sym,current = TRUE, a=0,b=1,c=2000,d,e,f,g="d")
{
if(current){
f<-as.numeric(substr(as.character(Sys.time()),start = 1,stop = 4))
d<-as.numeric(substr(as.character(Sys.time()),start = 6,stop = 7))-1
e<-as.numeric(substr(as.character(Sys.time()),start = 9,stop = 10))
}
require(data.table)
tryCatch(
suppressWarnings(
fread(paste0("http://ichart.yahoo.com/table.csv",
"?s=",sym,
"&a=",a,
"&b=",b,
"&c=",c,
"&d=",d,
"&e=",e,
"&f=",f,
"&g=",g,
"&ignore=.csv"),sep=",")),
error = function(e) NULL
)
}
When I run Google<-yahoo("GOOG"), this is the message I received:
trying URL 'http://ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000&d=8&e=13&f=2017&g=d&ignore=.csv'
Content type 'text/html; charset=utf-8' length unknown
downloaded 1078 bytes
So how to change that function make it work?
This code isn't working because the Yahoo Finance web service which you're trying to access was discontinued in May 2017. You will need to find another source for this data.

F#: DataContractJsonSerializer.WriteObject method

I am new to programming and F# is my first language.
Here are the relevant parts of my code:
let internal saveJsonToFile<'t> (someObject:'t) (filePath: string) =
use fileStream = new FileStream(filePath, FileMode.OpenOrCreate)
(new DataContractJsonSerializer(typeof<'t>)).WriteObject(fileStream, someObject)
let dummyFighter1 = { id = 1; name = "Dummy1"; location = "Here"; nationality = "Somalia"; heightInMeters = 2.0; weightInKgs = 220.0; weightClass = "Too fat"}
let dummyFighter2 = { id = 2; name = "Dummy2"; location = "There"; nationality = "Afghanistan"; heightInMeters = 1.8; weightInKgs = 80.0; weightClass = "Just Nice"}
let filePath = #"G:\User\Fighters.json"
saveJsonToFile dummyFighter1 filePath
saveJsonToFile dummyFighter2 filePath
When I run "saveJsonToFile dummyFighter1 filePath", the information is successfully saved. My problem is this: Once I run "saveJsonToFile dummyFighter2 filePath", it immediately replaces all the contents that are already in the file, i.e., all the information about dummyFighter1.
What changes should I make so that information about dummyFighter2 is appended to the file, instead of replacing information about dummyFighter1?
Change the way you open a file setting FileMode.OpenOrCreate to FileMode.Append. Append means "create or append" :
use fileStream = new FileStream(filePath, FileMode.Append)
From MSDN (https://msdn.microsoft.com/fr-fr/library/system.io.filemode%28v=vs.110%29.aspx) :
FileMode.Append opens the file if it exists and seeks to the end of the file, or
creates a new file. This requires FileIOPermissionAccess.Append
permission. FileMode.Append can be used only in conjunction with
FileAccess.Write. Trying to seek to a position before the end of the
file throws an IOException exception, and any attempt to read fails
and throws a NotSupportedException exception.

How to write a logout function for my django app?

Here is views.py:
def authent(request):
user = request.POST['username']
passw = request.POST['password']
featureDetail = []
loginrole = People_Login.objects.get(User_Name = user, Password = passw)
features = Role_FGroup_FSubGroup_FItems_Map.objects.filter(Role_Id = loginrole.id)
for p in features:
dic = {}
dic['ID'] = p.id
dic['Role_ID'] = p.Role_Id.id
dic['FGID'] = p.Feature_Group_Id.id
dic['FSGID'] = p.Feature_SubGroup_Id.id
dic['FIID'] = p.Feature_Items_Id.id
dic['SFGNAME'] = p.Feature_Group_Id.Name
dic['SFSGNAME'] = p.Feature_SubGroup_Id.Name
dic['SFINAME'] = p.Feature_Items_Id.Name
featureDetail.append(dic)
featuresgroups = Role_Feature_Group_Map.objects.filter(Role_Id = loginrole.Role_Id.id)
request.session['feature_list'] = featureDetail
request.session['featuresgroups'] = featuresgroups
return render_to_response('UAM/index.html',{"contacts":featureDetail,'len':len(featureDetail)-1,'test1':"shiva",'test2':"shiva","featuresgroups":featuresgroups})
For this authent function how to write my logout function
(as I am new to Django)? Please go easy and give me the code for logout function.
I suggest using Django's built in authentication features instead of rolling out your own. Otherwise, you're bound to make many mistakes (such as storing plain text passwords, which I see it's what you're doing) and reinvent many wheels (such as session handling, groups and permissions, etc). If you need to store more information about users than Django supports, you can do it in the form or user profiles.
Anyway, if by "logged on" you mean "having those values in the session", to "log out" you just need to remove them, no?
It really is this easy:
from django.contrib.auth import logout
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')