plugins can now respond to api

master
Kevin Froman 2019-02-08 12:53:28 -06:00
parent 64be7ebff3
commit 9d5aec1b78
4 changed files with 48 additions and 16 deletions

View File

@ -19,7 +19,7 @@
'''
from gevent.pywsgi import WSGIServer, WSGIHandler
from gevent import Timeout
import flask, cgi
import flask, cgi, uuid
from flask import request, Response, abort, send_from_directory
import sys, random, threading, hmac, hashlib, base64, time, math, os, json, socket
import core
@ -276,6 +276,7 @@ class API:
logger.info('Running api on %s:%s' % (self.host, self.bindPort))
self.httpServer = ''
self.pluginResponses = {}
self.queueResponse = {}
onionrInst.setClientAPIInst(self)
@ -458,14 +459,28 @@ class API:
@app.route('/apipoints/<path:subpath>')
def pluginEndpoints(subpath=''):
# TODO have a variable for the plugin to set data to that we can use for the response
pluginResponseCode = str(uuid.uuid4())
resp = 'success'
responseTimeout = 5
startTime = self._core._utils.getEpoch()
if len(subpath) > 1:
data = subpath.split('/')
if len(data) > 1:
plName = data[0]
events.event('pluginRequest', plName, subpath)
events.event('pluginRequest', {'name': plName, 'path': subpath, 'pluginResponse': pluginResponseCode}, onionr=onionrInst)
while True:
try:
resp = self.pluginResponses[pluginResponseCode]
except KeyError:
time.sleep(0.2)
if self._core._utils.getEpoch() - startTime > responseTimeout:
abort(504)
break
else:
break
else:
abort(404)
return Response('Success')
return Response(resp)
self.httpServer = WSGIServer((self.host, bindPort), app, log=None, handler_class=FDSafeHandler)
self.httpServer.serve_forever()

View File

@ -61,10 +61,9 @@ def call(plugin, event_name, data = None, pluginapi = None):
try:
attribute = 'on_' + str(event_name).lower()
# TODO: Use multithreading perhaps?
if hasattr(plugin, attribute):
#logger.debug('Calling event ' + str(event_name))
getattr(plugin, attribute)(pluginapi)
getattr(plugin, attribute)(pluginapi, data)
return True
except Exception as e:

View File

@ -22,7 +22,7 @@
import logger, config, threading, time, readline, datetime
from onionrblockapi import Block
import onionrexceptions, onionrusers
import locale, sys, os
import locale, sys, os, json
locale.setlocale(locale.LC_ALL, '')
@ -161,7 +161,7 @@ class OnionrMail:
'''
entering = True
while entering:
self.getSentList()
self.get_sent_list()
logger.info('Enter a block number or -q to return')
try:
choice = input('>')
@ -188,18 +188,19 @@ class OnionrMail:
return
def getSentList(self):
def get_sent_list(self, display=True):
count = 1
self.sentboxList = []
self.sentMessages = {}
for i in self.sentboxTools.listSent():
self.sentboxList.append(i['hash'])
self.sentMessages[i['hash']] = (i['message'], i['peer'])
if display:
logger.info('%s. %s - %s - %s' % (count, i['hash'], i['peer'][:12], i['date']))
count += 1
return json.dumps(self.sentMessages)
def draftMessage(self, recip=''):
def draft_message(self, recip=''):
message = ''
newLine = ''
subject = ''
@ -248,7 +249,7 @@ class OnionrMail:
blockID = self.myCore.insertBlock(message, header='pm', encryptType='asym', asymPeer=recip, sign=self.doSigs, meta={'subject': subject})
self.sentboxTools.addToSent(blockID, recip, message)
def toggleSigning(self):
def toggle_signing(self):
self.doSigs = not self.doSigs
def menu(self):
@ -276,9 +277,9 @@ class OnionrMail:
elif choice in (self.strings.mainMenuChoices[1], '2'):
self.sentbox()
elif choice in (self.strings.mainMenuChoices[2], '3'):
self.draftMessage()
self.draft_message()
elif choice in (self.strings.mainMenuChoices[3], '4'):
self.toggleSigning()
self.toggle_signing()
elif choice in (self.strings.mainMenuChoices[4], '5'):
logger.info('Goodbye.')
break
@ -288,6 +289,12 @@ class OnionrMail:
logger.warn('Invalid choice.')
return
def on_pluginrequest(api, data=None):
if data['name'] == 'mail':
path = data['path']
if path.split('/')[1] == 'sentbox':
api.get_onionr().clientAPIInst.pluginResponses[data['pluginResponse']] = OnionrMail(api).get_sent_list(display=False)
return
def on_init(api, data = None):
'''

View File

@ -18,6 +18,7 @@
*/
pms = ''
sentbox = ''
threadPart = document.getElementById('threads')
threadPlaceholder = document.getElementById('threadPlaceholder')
tabBtns = document.getElementById('tabBtns')
@ -48,10 +49,10 @@ function setActiveTab(tabName){
threadPart.innerHTML = ""
switch(tabName){
case 'inbox':
getInbox();
getInbox()
break
case 'sentbox':
console.log(tabName)
getSentbox()
break
case 'drafts':
console.log(tabName)
@ -132,7 +133,17 @@ function getInbox(){
if (! showed){
threadPlaceholder.style.display = 'block'
}
}
function getSentbox(){
fetch('/apipoints/mail/sentbox', {
headers: {
"token": webpass
}})
.then((resp) => resp.text()) // Transform the data into json
.then(function(data) {
sentbox = data
})
}
fetch('/getblocksbytype/pm', {