From 9d5aec1b78c062a0122df3ff1e941f20c82e6dbc Mon Sep 17 00:00:00 2001 From: Kevin Froman Date: Fri, 8 Feb 2019 12:53:28 -0600 Subject: [PATCH] plugins can now respond to api --- onionr/api.py | 21 +++++++++++++--- onionr/onionrevents.py | 3 +-- .../static-data/default-plugins/pms/main.py | 25 ++++++++++++------- onionr/static-data/www/mail/mail.js | 15 +++++++++-- 4 files changed, 48 insertions(+), 16 deletions(-) diff --git a/onionr/api.py b/onionr/api.py index ac1a7eaa..1aaed6b5 100755 --- a/onionr/api.py +++ b/onionr/api.py @@ -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/') 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() diff --git a/onionr/onionrevents.py b/onionr/onionrevents.py index 26fdc093..0a2c48f1 100755 --- a/onionr/onionrevents.py +++ b/onionr/onionrevents.py @@ -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: diff --git a/onionr/static-data/default-plugins/pms/main.py b/onionr/static-data/default-plugins/pms/main.py index bc16fa49..099e442c 100755 --- a/onionr/static-data/default-plugins/pms/main.py +++ b/onionr/static-data/default-plugins/pms/main.py @@ -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']) - - logger.info('%s. %s - %s - %s' % (count, i['hash'], i['peer'][:12], i['date'])) + 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): ''' diff --git a/onionr/static-data/www/mail/mail.js b/onionr/static-data/www/mail/mail.js index 71e592e9..daf9e115 100755 --- a/onionr/static-data/www/mail/mail.js +++ b/onionr/static-data/www/mail/mail.js @@ -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', {