<?php
class custom_cloudconvert {
	function init() {
		global $locale;
		$this->localeSection = "Custom Actions: CloudConvert";
		$this->APIKey = 'MPMPjEJ8lgR97CA7JcE3zJ8V1OIsOdUOquDwGj37omzOve1vQdVapddjGxL9swrVMuh4Or6kj7Yi1ujDsgWxdQ';
		$this->JSconfig = array(
			"title" => $locale->get("CloudConvert", $this->localeSection),
			"iconCls" => 'fa fa-fw fa-cloud',
			"popup" => true,
			"requiredUserPerms" => array("download", "upload")
		);
	}
	function run() {
		global $log, $fileman, $fm, $str;
		$fileman->checkPerms("download");
		$ext = $fm->getExtension($this->data['fileName']);
		$url = 'https://api.cloudconvert.org/conversiontypes?inputformat='.$str->forURL($ext);
		$http = new Guzzle\Http\Client($url);
		try {
			$response = $http->get()->send();
		} catch (Guzzle\Http\Exception\BadResponseException $e) {
			echo 'Bad server response: '.$e->getResponse()->getStatusCode();
			echo $e->getResponse();
			exit();
		} catch (Guzzle\Http\Exception\CurlException $e) {
			echo 'Connection to CloudConvert server failed: '.$e->getErrorNo();
			echo $e->getMessage();
			exit();
		}
		if ($response->isSuccessful()) {
			$rs = $response->json();
			require($this->path."/display.php");
		}
	}
	function createProcess() {
		global $str, $fm;
		$ext = $fm->getExtension($this->data['fileName']);
		$url = 'https://api.cloudconvert.org/process';
		$http = new Guzzle\Http\Client();
		try {
			$req = $http->post($url, array('X-CloudConvert-ApiKey' => $this->APIKey), array(
				'apikey' => $this->APIKey,
				'inputformat' => $ext,
				'outputformat' => $this->targetFormat
			));
			$response = $req->send();
		} catch (Guzzle\Http\Exception\BadResponseException $e) {
			$rs = $e->getResponse()->json();
			if ($rs) {
				jsonFeedback(false, 'CloudConvert server error: '.$rs['error']);
			} else {
				echo 'Bad server response: '.$e->getResponse()->getStatusCode();
				echo $e->getResponse();
				exit();
			}
		} catch (Guzzle\Http\Exception\CurlException $e) {
			echo 'Connection to CloudConvert server failed: '.$e->getErrorNo();
			echo $e->getMessage();
			exit();
		}
		if ($response->isSuccessful()) {
			$rs = $response->json();
			if ($rs['url']) {
				return $rs['url'];
			} else {
				jsonFeedback(false, 'Missing process URL');
			}
		} else {
			jsonFeedback(false, 'Failed to create conversion process');
		}
	}
	function requestConversion() {
		global $str;
		$this->targetFormat = $str->fromHTML($_POST['format']);
		$url = $this->createProcess();
		if (strtolower(substr($url, 0, 6)) != 'https:') {
			$url = 'https:'.$url;
		}
		$webLinkUrl = $this->weblinks->getOneTimeDownloadLink($this->data['filePath']);
		if (!$webLinkUrl) {
			jsonFeedback(false, 'Failed to create weblink');
		}
		$http = new Guzzle\Http\Client();
		try {
			$response = $http->post($url, false, array(
				'input' => 'download',
				'file' => $webLinkUrl,
				'filename' => $this->data['fileName'],
				'outputformat' => $this->targetFormat
			))->send();
		} catch (Guzzle\Http\Exception\BadResponseException $e) {
			echo 'Bad server response: '.$e->getResponse()->getStatusCode();
			echo $e->getResponse();
			exit();
		} catch (Guzzle\Http\Exception\CurlException $e) {
			if ($this->APIerror['code'] == '7') {
				echo 'Unable to connect to CloudConvert server';
			} else {
				echo 'Connection failed: '.$e->getErrorNo();
				echo $e->getMessage();
			}
			exit();
		}
		if ($response->isSuccessful()) {
			$rs = $response->json();
			jsonOutput(array(
				'success' => true,
				'msg' => 'CloudConvert: '. $rs['message'],
				'url' => $url
			));
		}
	}
	function getStatus() {
		global $str, $fm;
		$url = $str->fromHTML($_POST['statusURL']);
		$http = new Guzzle\Http\Client();
		try {
			$response = $http->get($url)->send();
		} catch (Guzzle\Http\Exception\BadResponseException $e) {
			$e->getResponse()->getStatusCode();
			$rs = $e->getResponse()->json();
			jsonOutput(array(
				'success' => false,
				'msg' => 'CloudConvert: '.$rs['message'],
				'step' => $rs['step'],
				'percent' => $rs['percent'],
				'output' => $rs['output']
			));
		} catch (Guzzle\Http\Exception\CurlException $e) {
			if ($this->APIerror['code'] == '7') {
				echo 'Unable to connect to CloudConvert server';
			} else {
				echo 'Connection failed: '.$e->getErrorNo();
				echo $e->getMessage();
			}
			exit();
		}
		if ($response->isSuccessful()) {
			$rs = $response->json();
			$rs['output']['size'] = $fm->formatFileSize($rs['output']['size']);
			jsonOutput(array(
				'success' => true,
				'msg' => 'CloudConvert: '.$rs['message'],
				'step' => $rs['step'],
				'percent' => $rs['percent'],
				'output' => $rs['output']
			));
		}
	}
}