From a5c1eb0a9b46c2463011f27a3edd58fbf4f32876 Mon Sep 17 00:00:00 2001 From: Olivier Paroz Date: Tue, 18 Aug 2015 03:16:49 +0200 Subject: Add Thumbnails API --- utility/eventsource.php | 95 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 utility/eventsource.php (limited to 'utility') diff --git a/utility/eventsource.php b/utility/eventsource.php new file mode 100644 index 00000000..63bf1d72 --- /dev/null +++ b/utility/eventsource.php @@ -0,0 +1,95 @@ + + * @author Felix Moeller + * @author Morris Jobke + * @author Robin Appelman + * @author Thomas Müller + * @author Vincent Petry + * @author Olivier Paroz + * + * @copyright Copyright (c) 2015, ownCloud, Inc. + * @copyright Olivier Paroz 2015 + */ + +namespace OCA\Gallery\Utility; + +/** + * Class EventSource + * + * Wrapper for server side events (http://en.wikipedia.org/wiki/Server-sent_events) + * + * This version is tailored for the Gallery app, do not use elsewhere! + * + * @todo Replace with a library + * + * @package OCA\Gallery\Controller + */ +class EventSource implements \OCP\IEventSource { + + /** + * @var bool + */ + private $started = false; + + protected function init() { + if ($this->started) { + return; + } + $this->started = true; + + // prevent php output buffering, caching and nginx buffering + while (ob_get_level()) { + ob_end_clean(); + } + header('Cache-Control: no-cache'); + header('X-Accel-Buffering: no'); + header("Content-Type: text/event-stream"); + flush(); + } + + /** + * Sends a message to the client + * + * If only one parameter is given, a typeless message will be sent with that parameter as data + * + * @param string $type + * @param mixed $data + * + * @throws \BadMethodCallException + */ + public function send($type, $data = null) { + if ($data and !preg_match('/^[A-Za-z0-9_]+$/', $type)) { + throw new \BadMethodCallException('Type needs to be alphanumeric (' . $type . ')'); + } + $this->init(); + if (is_null($data)) { + $data = $type; + $type = null; + } + + if ($type) { + echo 'event: ' . $type . PHP_EOL; + } + echo 'data: ' . json_encode($data) . PHP_EOL; + + echo PHP_EOL; + flush(); + } + + /** + * Closes the connection of the event source + * + * It's best to let the client close the stream + */ + public function close() { + $this->send( + '__internal__', 'close' + ); + } +} -- cgit v1.2.3