plugins can now respond to api

This commit is contained in:
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.pywsgi import WSGIServer, WSGIHandler
from gevent import Timeout from gevent import Timeout
import flask, cgi import flask, cgi, uuid
from flask import request, Response, abort, send_from_directory from flask import request, Response, abort, send_from_directory
import sys, random, threading, hmac, hashlib, base64, time, math, os, json, socket import sys, random, threading, hmac, hashlib, base64, time, math, os, json, socket
import core import core
@ -276,6 +276,7 @@ class API:
logger.info('Running api on %s:%s' % (self.host, self.bindPort)) logger.info('Running api on %s:%s' % (self.host, self.bindPort))
self.httpServer = '' self.httpServer = ''
self.pluginResponses = {}
self.queueResponse = {} self.queueResponse = {}
onionrInst.setClientAPIInst(self) onionrInst.setClientAPIInst(self)
@ -458,14 +459,28 @@ class API:
@app.route('/apipoints/<path:subpath>') @app.route('/apipoints/<path:subpath>')
def pluginEndpoints(subpath=''): def pluginEndpoints(subpath=''):
# TODO have a variable for the plugin to set data to that we can use for the response # 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: if len(subpath) > 1:
data = subpath.split('/') data = subpath.split('/')
if len(data) > 1: if len(data) > 1:
plName = data[0] 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: else:
abort(404) abort(404)
return Response('Success') return Response(resp)
self.httpServer = WSGIServer((self.host, bindPort), app, log=None, handler_class=FDSafeHandler) self.httpServer = WSGIServer((self.host, bindPort), app, log=None, handler_class=FDSafeHandler)
self.httpServer.serve_forever() self.httpServer.serve_forever()

View File

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

View File

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

View File

@ -18,6 +18,7 @@
*/ */
pms = '' pms = ''
sentbox = ''
threadPart = document.getElementById('threads') threadPart = document.getElementById('threads')
threadPlaceholder = document.getElementById('threadPlaceholder') threadPlaceholder = document.getElementById('threadPlaceholder')
tabBtns = document.getElementById('tabBtns') tabBtns = document.getElementById('tabBtns')
@ -48,10 +49,10 @@ function setActiveTab(tabName){
threadPart.innerHTML = "" threadPart.innerHTML = ""
switch(tabName){ switch(tabName){
case 'inbox': case 'inbox':
getInbox(); getInbox()
break break
case 'sentbox': case 'sentbox':
console.log(tabName) getSentbox()
break break
case 'drafts': case 'drafts':
console.log(tabName) console.log(tabName)
@ -132,7 +133,17 @@ function getInbox(){
if (! showed){ if (! showed){
threadPlaceholder.style.display = 'block' 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', { fetch('/getblocksbytype/pm', {