Image now are working!

parent dcd83891
...@@ -26,6 +26,12 @@ from dmlib.utils import webutils as wu ...@@ -26,6 +26,12 @@ from dmlib.utils import webutils as wu
import json import json
import logging import logging
from domotika.db import dmdb from domotika.db import dmdb
try:
#python2
from urllib import urlencode
except ImportError:
#python3
from urllib.parse import urlencode
try: try:
...@@ -34,6 +40,18 @@ except: ...@@ -34,6 +40,18 @@ except:
log = logging.getLogger('Core') log = logging.getLogger('Core')
HEADERS={
'User-Agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, sdch",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"DNT": "1",
"Host": "api.openweathermap.org",
"Pragma": "no-cache",
"Upgrade-Insecure-Request": "1",
}
class OWMWeather(object): class OWMWeather(object):
usecity=False usecity=False
...@@ -56,11 +74,13 @@ class OWMWeather(object): ...@@ -56,11 +74,13 @@ class OWMWeather(object):
def _getReport(self): def _getReport(self):
log.debug("Weather get report") log.debug("Weather get report")
if self.usecity: if self.usecity:
page="http://api.openweathermap.org/data/2.5/weather?q="+str(self.city)+"&units=metric" page="http://api.openweathermap.org/data/2.5/weather?"+urlencode({'q': str(self.city)})+"&units=metric"
else: else:
page="http://api.openweathermap.org/data/2.5/weather?lat="+str(self.lat)+"&lon="+str(self.lon)+"&mode=json&units=metric" page="http://api.openweathermap.org/data/2.5/weather?lat="+str(self.lat)+"&lon="+str(self.lon)+"&mode=json&units=metric"
page+="&APPID="+str(self.owmid) page+="&APPID="+str(self.owmid)
cb=wu.getPage(page, headers={'x-api-key': str(self.owmid)}).addCallbacks(self.onData, self.onError) log.info("Requesting for "+str(page))
uagent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"
cb=wu.getPage(page, headers=HEADERS).addCallbacks(self.onData, self.onError)
def updateDatabase(self): def updateDatabase(self):
for k in self.data.keys(): for k in self.data.keys():
......
...@@ -939,3 +939,16 @@ def getVoiceCommandList(): ...@@ -939,3 +939,16 @@ def getVoiceCommandList():
qstring="SELECT speech_string FROM speech_actions WHERE active=1" qstring="SELECT speech_string FROM speech_actions WHERE active=1"
return runQuery(qstring) return runQuery(qstring)
def getScreenshotUri(target):
qstring="select screenshot from mediasources where button_name LIKE '"+target+"%' limit 1"
return runQuery(qstring)
def getClimaUniques():
qstring="select name, value from uniques where name='climastatus' OR name='last.rain' OR name LIKE 'owm.%'"
return runQuery(qstring)
def getThermostats():
qstring="select t.button_name, t.setval, a.status, t.function from thermostats as t, anastatus as a WHERE a.ananame=t.name"
return runQuery(qstring)
...@@ -2455,6 +2455,21 @@ class domotikaService(service.Service): ...@@ -2455,6 +2455,21 @@ class domotikaService(service.Service):
def web_on_getScreenshotList(self, screenshot=True): def web_on_getScreenshotList(self, screenshot=True):
return dmdb.getScreenshotList(screenshot=screenshot) return dmdb.getScreenshotList(screenshot=screenshot)
def web_on_getScreenshot(self, target):
def imageReturn(img):
return img
def prepareScreenshot(res):
if res:
return wu.getPage(res[0][0]).addCallback(imageReturn)
return False
return dmdb.getScreenshotUri(target).addCallback(prepareScreenshot)
def web_on_getClimaUniques(self):
return dmdb.getClimaUniques()
def web_on_getThermostats(self):
return dmdb.getThermostats()
def web_on_getChartData(self, chartname): def web_on_getChartData(self, chartname):
log.debug('GET CHART DATA FOR '+str(chartname)) log.debug('GET CHART DATA FOR '+str(chartname))
return dmdb.getChartData(chartname).addCallback(self.getChartData, chartname) return dmdb.getChartData(chartname).addCallback(self.getChartData, chartname)
......
...@@ -11,14 +11,15 @@ from dmlib.utils import webutils as wu ...@@ -11,14 +11,15 @@ from dmlib.utils import webutils as wu
import hashlib import hashlib
import hmac import hmac
import six import six
import time
from Queue import Queue
import uuid
from domotika.singleton import messengerlinks from domotika.singleton import messengerlinks
_MESSENGER_LINKS = messengerlinks.MessengerLinkRegistry() _MESSENGER_LINKS = messengerlinks.MessengerLinkRegistry()
_MESSENGER_PSID = messengerlinks.MessengerPSIDRegistry() _MESSENGER_PSID = messengerlinks.MessengerPSIDRegistry()
try: try:
#python2 #python2
from urllib import urlencode from urllib import urlencode
...@@ -68,6 +69,13 @@ def messengerValidator(): ...@@ -68,6 +69,13 @@ def messengerValidator():
return checkRequest return checkRequest
class MessengerMessage(object):
def __init__(self, headers, payload, uri):
self.headers = headers
self.payload = payload
self.uri = uri
class MessengerCore(object): class MessengerCore(object):
def _cfgGet(self, keyword): def _cfgGet(self, keyword):
...@@ -78,6 +86,8 @@ class MessengerBot(BotCore, MessengerCore): ...@@ -78,6 +86,8 @@ class MessengerBot(BotCore, MessengerCore):
path = "messenger" path = "messenger"
graphuri = 'https://graph.facebook.com/v2.6' graphuri = 'https://graph.facebook.com/v2.6'
sendQueue = Queue()
sendlock = False
#graphuri = 'http://192.168.4.2/v2.6' #graphuri = 'http://192.168.4.2/v2.6'
@property @property
...@@ -106,7 +116,17 @@ class MessengerBot(BotCore, MessengerCore): ...@@ -106,7 +116,17 @@ class MessengerBot(BotCore, MessengerCore):
def _dataError(self, res): def _dataError(self, res):
log.info('Messenger BOT Datasent ERROR') log.info('Messenger BOT Datasent ERROR')
log.error(res) log.error(res)
try:
log.debug(res.value.reasons[0].printTraceback()) log.debug(res.value.reasons[0].printTraceback())
except:
pass
def _sendRaw(self):
if not self.sendQueue.empty() and not self.sendLock:
message = self.sendQueue.get()
return wu.getPage(message.uri, method='POST', headers=message.headers,
postdata=message.payload).addCallbacks(self._dataSent, self._dataError)
...@@ -207,16 +227,19 @@ class MessengerBot(BotCore, MessengerCore): ...@@ -207,16 +227,19 @@ class MessengerBot(BotCore, MessengerCore):
if txt == u'hello' or txt == u'ciao': if txt == u'hello' or txt == u'ciao':
self.sendMessage(senderid, 'Hello %s, how can i help you?' %(_MESSENGER_PSID.get_link(senderid))) self.sendMessage(senderid, 'Hello %s, how can i help you?' %(_MESSENGER_PSID.get_link(senderid)))
elif txt == u'?' or txt == u'help': elif txt == u'?' or txt == u'help':
self.sendMessage(senderid, 'Ok, devo ancora implementare l\'aiuto!') self.sendMessage(senderid, 'Ok, devo ancora implementare l\'aiuto! Sorry for that!')
self.sendMessage(senderid, 'Anyway, i comandi che hai sono: "command list", "screenshot list", "screenshot" e "clima".')
self.sendMessage(senderid, 'Qualsiasi altro comando viene interpretato come un potenziale comando vocale.')
elif txt == u'logout': elif txt == u'logout':
self.sendMessage(senderid, 'Ok, devo ancora implementare anche il logout') self.sendMessage(senderid, 'Ok, devo ancora implementare anche il logout')
elif txt == u'command list': elif txt == u'command list' or txt == 'cmd list':
self.sendCommandList(senderid) self.sendCommandList(senderid)
elif txt == u'screenshot list': elif txt == u'screenshot list' or txt==u'ss list':
self.sendScreenshotList(senderid) self.sendScreenshotList(senderid)
elif txt.startswith('screenshot '): elif txt.startswith('screenshot ') or txt.startswith('ss '):
self.sendScreenshot(senderid, " ".join(txt.split()[1:])) self.sendScreenshot(senderid, " ".join(txt.split()[1:]))
elif txt == u'clima':
self.sendClima(senderid)
else: else:
self.core.voiceReceived(txt, confidence=1.0, lang="it").addCallback(voiceResult) self.core.voiceReceived(txt, confidence=1.0, lang="it").addCallback(voiceResult)
...@@ -246,20 +269,39 @@ class MessengerBot(BotCore, MessengerCore): ...@@ -246,20 +269,39 @@ class MessengerBot(BotCore, MessengerCore):
self.sendMessage(senderid, "Target list for string/voice commands (call them with the right action like up,down,open,close and so on.):") self.sendMessage(senderid, "Target list for string/voice commands (call them with the right action like up,down,open,close and so on.):")
self.core.getVoiceCommandList().addCallback(pushList) self.core.getVoiceCommandList().addCallback(pushList)
def sendScreenshotList(self, senderid): def sendScreenshotList(self, recipient_id):
def pushList(res): def pushList(res):
for r in res: for r in res:
self.sendMessage(senderid, " * "+str(r[0])) self.sendMessage(recipient_id, " * "+str(r[0]))
self.sendMessage(senderid, "Cam list:") self.sendMessage(recipient_id, "Cam list:")
self.core.getScreenshotList().addCallback(pushList) self.core.getScreenshotList().addCallback(pushList)
def sendScreenshot(self, senderid, target): def sendScreenshot(self, recipient_id, target):
def pushImage(res): def pushImage(res):
self.sendImageMessage(recipient_id, res) if res:
self.sendImageMessageData(recipient_id, res)
else:
self.sendMessage(recipient_id, 'Cannot retrieve image of '+str(target))
if target.endswith('%'):
target=target[:-1]
if len(target) > 0:
self.core.getScreenshot(target).addCallback(pushImage) self.core.getScreenshot(target).addCallback(pushImage)
def sendClima(self, recipient_id):
def pushClima(res):
for r in res:
if r[0] == 'last.rain':
msg=r[0]+": "+time.strftime('%d-%m-%Y %H:%M:%S', time.localtime(int(r[1])))
else:
msg=r[0]+": "+str(r[1])
self.sendMessage(recipient_id, msg)
def pushThermo(res):
for r in res:
msg=r[0]+": set "+str(r[1])+" read "+str(float(r[2])/10)+" function "+r[3]
self.sendMessage(recipient_id, msg)
return self.core.getClimaUniques().addCallback(pushClima)
self.core.getThermostats().addCallback(pushThermo)
def sendMessage(self, recipient_id, message): def sendMessage(self, recipient_id, message):
payload = { payload = {
...@@ -288,6 +330,42 @@ class MessengerBot(BotCore, MessengerCore): ...@@ -288,6 +330,42 @@ class MessengerBot(BotCore, MessengerCore):
} }
return self.sendAPI(payload) return self.sendAPI(payload)
def sendImageMessageData(self, recipient_id, imagedata):
payload = {
'recipient': {
'id': recipient_id
},
'message': {
'attachment': {
'type': 'image',
'payload': {}
}
}
}
fname=str(uuid.uuid4().get_hex())+'.jpg'
bond="------------------------"+str(uuid.uuid4().get_hex())[:16]
data="--"+bond+"\r\n"
data+="Content-Disposition: form-data; name=\"recipient\"\r\n\r\n"
data+="{\"id\": \""+str(recipient_id)+"\"}\r\n"
data+="--"+bond+"\r\n"
data+="Content-Disposition: form-data; name=\"message\"\r\n\r\n"
data+='{"attachment":{"type":"image", "payload":{}}}'+"\r\n"
data+="--"+bond+"\r\n"
data+='Content-Disposition: form-data; name="filedata"; filename="'+fname+'"'+"\r\n"
data+='Content-Type: image/jpeg'+"\r\n\r\n"
data+=str(imagedata)
data+="\r\n--"+bond+"--\r\n"
headers={
'Accept': '*/*',
'Content-Type': 'multipart/form-data; boundary='+bond
}
request_endpoint=self.graphuri+'/me/messages'
request_uri = request_endpoint+'?'+urlencode(self.auth_args)
return wu.getPage(request_uri, agent="curl/7.50.1", method='POST', headers=headers,
postdata=data, expect100=True).addCallbacks(self._dataSent, self._dataError)
def sendAuthRequest(self, recipient_id): def sendAuthRequest(self, recipient_id):
payload = { payload = {
'recipient': { 'recipient': {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment