<?php
/*
	View with Box View...
*/
class custom_box_view
{
	function init()
	{
		global $locale;
		$this->APIKey = 'h52erfym6jpfarl92ptwv51jusx2zxmr';
		$this->URL = 'https://upload.view-api.box.com/1/documents';
		$this->sessionsURL = 'https://view-api.box.com/1/sessions';
		$this->JSconfig = array(
			"title" => $locale->get("Box View", 'Custom Actions: Box View'),
			"iconCls" => 'fa fa-fw fa-cloud',
			"extensions" => array(
				'pdf', 'doc', 'docx', 'ppt', 'pptx',
				'xls', 'xlsx'
			),
			"popup" => true,
			"requiredUserPerms" => array("download"),
			'loadingMsg' => $locale->get('Loading...'),
		);
	}

	function run() {
		$http = new Guzzle\Http\Client();
		$req = $http->post($this->URL)
			->addHeader('Authorization', 'Token ' . $this->APIKey)
			->addPostFields(array('name' => $this->data['fileName']))
			->addPostFile('file', $this->data['filePath']);
		try {
			$rs = $req->send();
		} catch (Guzzle\Http\Exception\BadResponseException $e) {
			try {
				$r = $e->getResponse()->json();
			} catch (Guzzle\Common\Exception\RuntimeException $e) {}
			$statusCode = $e->getResponse()->getStatusCode();
			if ($statusCode == '429') {
				echo 'The Box View API uses rate limiting to prevent too many requests in a short period of time.<br>';
			}
			if ($r['message']) {
				echo $r['type'] . ': ' . $r['message'];
				if ($r['details'][0]['field']) {
					echo "\r\n<br>\r\n";
					echo $r['details'][0]['field'] . ' -> ' . $r['details'][0]['message'];
				}
			}
		} catch (Guzzle\Http\Exception\CurlException $e) {echo $e->getMessage();}
		if ($rs && $rs->isSuccessful()) {
			$serverResponse = $rs->json();
			if ($serverResponse['id']) {
				$this->openSession($serverResponse['id']);
			}
		}
	}
	function openSession($docId) {
		$http = new Guzzle\Http\Client();
		$req = $http->post($this->sessionsURL)
			->addHeader('Authorization', 'Token ' . $this->APIKey)
			->setHeader('Content-Type', 'application/json')
			->setBody(json_encode(array(
				'document_id' => $docId
			)));
		try {
			$rs = $req->send();
		} catch (Guzzle\Http\Exception\BadResponseException $e) {
			try {
				$r = $e->getResponse()->json();
			} catch (Guzzle\Common\Exception\RuntimeException $e) {}
			$statusCode = $e->getResponse()->getStatusCode();
			if ($statusCode == '202') {
				echo 'The uploaded document has not been yet converted to a viewable format.<br>';
			}
			//$retryAfter = $e->getResponse()->getHeader('Retry-After');
			if ($r['message']) {
				echo $r['type'] . ': ' . $r['message'];
				if ($r['details'][0]['field']) {
					echo "\r\n<br>\r\n";
					echo $r['details'][0]['field'] . ' -> ' . $r['details'][0]['message'];
				}
			}
		} catch (Guzzle\Http\Exception\CurlException $e) {
			echo $e->getMessage();
		}
		if ($rs && $rs->isSuccessful()) {
			if ($rs->getStatusCode() == 202) {
				$waitTime = (int) $rs->getHeader('Retry-After');
				if ($waitTime < 30) {
					sleep($waitTime);
					$this->openSession($docId);
					exit();
				} else {
					exit('Box View requires more than 30 seconds to process the request.  The action has been canceled.');
				}
			}
			$serverResponse = $rs->json();
			if ($serverResponse['urls']['view']) {
				global $log;
				$log->add(false, "preview", array(
					"relative_path" => $this->data['relativePath'],
					"full_path" => $this->data['filePath'],
					"method" => "Box View"
				));
				header('Location: ' . $serverResponse['urls']['view']);
				exit();
			} else {
				echo 'Unexpected Box server response';
			}
		}
	}
}