ExportDownload.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. namespace App\Tools;
  3. use Illuminate\Support\Str;
  4. use Illuminate\Support\Facades\Log;
  5. use Illuminate\Support\Facades\Storage;
  6. use Illuminate\Support\Facades\App;
  7. use Symfony\Component\Process\Process;
  8. use Symfony\Component\Process\Exception\ProcessFailedException;
  9. use Illuminate\Support\Facades\Cache;
  10. use App\Tools\Export;
  11. class ExportDownload
  12. {
  13. protected $statusKey = 'export/status';
  14. protected $statusExpiry = 3600;
  15. protected $currStatusKey = '';
  16. protected $queryId = 'id';
  17. protected $realFilename = 'index'; //压缩包里的文件名
  18. protected $zipFilename = 'file.zip';
  19. protected $downloadUrl = null;
  20. protected $format = 'tex';
  21. protected $debug = false;
  22. protected $logs = [];
  23. /**
  24. * Create a new command instance.
  25. *
  26. * @return void
  27. */
  28. public function __construct($options = [])
  29. {
  30. if (isset($options['format'])) {
  31. $this->format = $options['format'];
  32. }
  33. if (isset($options['debug'])) {
  34. $this->debug = $options['debug'];
  35. }
  36. if (isset($options['filename'])) {
  37. $this->realFilename = $options['filename'];
  38. }
  39. $this->queryId = $options['queryId'];
  40. $this->zipFilename = $this->queryId . '.zip';
  41. $this->currStatusKey = $this->statusKey . '/' . $this->queryId;
  42. }
  43. /**
  44. * progress: 0-1, error -1
  45. * message: string
  46. */
  47. public function setStatus($progress, $message = '')
  48. {
  49. $this->logs[] = $message;
  50. $data = [
  51. 'progress' => $progress,
  52. 'message' => $message,
  53. 'log' => $this->logs,
  54. 'content-type' => 'application/zip',
  55. ];
  56. if ($this->downloadUrl) {
  57. $data['url'] = $this->downloadUrl;
  58. }
  59. Cache::put(
  60. $this->currStatusKey,
  61. $data,
  62. $this->statusExpiry
  63. );
  64. $percent = (int)($progress * 100);
  65. return "[{$percent}%]" . $message;
  66. }
  67. public function getStatus()
  68. {
  69. return Cache::get($this->currStatusKey);
  70. }
  71. public function upload(string $type, $sections, $bookMeta)
  72. {
  73. $outputFilename = Str::uuid();
  74. $m = new \Mustache_Engine(array(
  75. 'entity_flags' => ENT_QUOTES,
  76. 'delimiters' => '[[ ]]',
  77. 'escape' => function ($value) {
  78. return $value;
  79. }
  80. ));
  81. $tex = array();
  82. $_format = 'md';
  83. $tplFile = resource_path("mustache/" . $type . '/' . $_format . "/main." . $_format);
  84. $tpl = file_get_contents($tplFile);
  85. $texContent = $m->render($tpl, $bookMeta);
  86. $tex[] = [
  87. 'name' => 'main.' . $_format,
  88. 'content' => $texContent
  89. ];
  90. foreach ($sections as $key => $section) {
  91. $tplFile = resource_path("mustache/" . $type . '/' . $_format . "/section." . $_format);
  92. $tpl = file_get_contents($tplFile);
  93. $texContent = $m->render($tpl, $section['body']);
  94. $tex[] = [
  95. 'name' => $section['name'],
  96. 'content' => $texContent
  97. ];
  98. }
  99. Log::debug('footnote start');
  100. //footnote
  101. $tplFile = resource_path("mustache/" . $_format . "/footnote." . $_format);
  102. if (
  103. isset($GLOBALS['note']) &&
  104. is_array($GLOBALS['note']) &&
  105. count($GLOBALS['note']) > 0 &&
  106. file_exists($tplFile)
  107. ) {
  108. $tpl = file_get_contents($tplFile);
  109. $texContent = $m->render($tpl, ['footnote' => $GLOBALS['note']]);
  110. $tex[] = [
  111. 'name' => 'footnote.' . $_format,
  112. 'content' => $texContent
  113. ];
  114. }
  115. Log::debug('footnote finished');
  116. $this->setStatus(0.95, 'export content done. tex count=' . count($tex));
  117. Log::debug('export content done.', ['tex_count' => count($tex)]);
  118. //upload
  119. $fileDate = '';
  120. switch ($this->format) {
  121. case 'tex':
  122. $data = Export::ToPdf($tex);
  123. if ($data['ok']) {
  124. $this->info($data['content-type']);
  125. $fileDate = $data['data'];
  126. } else {
  127. $this->error($data['code'] . '-' . $data['message']);
  128. }
  129. break;
  130. default:
  131. $file = array();
  132. foreach ($tex as $key => $section) {
  133. $file[] = $section['content'];
  134. }
  135. $fileDate = implode('', $file);
  136. break;
  137. }
  138. $dir = "tmp/export/{$type}/" . $this->format . "/";
  139. $mdFilename = $dir . $outputFilename . '.md';
  140. Storage::disk('local')->put($mdFilename, $fileDate);
  141. Log::debug('markdown saved', ['filename' => $mdFilename]);
  142. if ($this->format === 'markdown') {
  143. $filename = $mdFilename;
  144. } else {
  145. $filename = $dir . $outputFilename . '.' . $this->format;
  146. Log::debug('tmp saved', ['filename' => $filename]);
  147. $absoluteMdPath = Storage::disk('local')->path($mdFilename);
  148. $absoluteOutputPath = Storage::disk('local')->path($filename);
  149. //$command = "pandoc pandoc1.md --reference-doc tpl.docx -o pandoc1.docx";
  150. $command = ['pandoc', $absoluteMdPath, '-o', $absoluteOutputPath];
  151. if ($this->format === 'docx') {
  152. $tplFile = resource_path("template/docx/paper.docx");
  153. array_push($command, '--reference-doc');
  154. array_push($command, $tplFile);
  155. }
  156. Log::debug('pandoc start', ['command' => $command, 'format' => $this->format]);
  157. $process = new Process($command);
  158. $process->run();
  159. if (!$process->isSuccessful()) {
  160. throw new ProcessFailedException($process);
  161. }
  162. echo $process->getOutput();
  163. Log::debug('pandoc end', ['command' => $command]);
  164. }
  165. $zipDir = storage_path('app/export/zip');
  166. if (!is_dir($zipDir)) {
  167. $res = mkdir($zipDir, 0755, true);
  168. if (!$res) {
  169. Log::error('mkdir fail path=' . $zipDir);
  170. return 1;
  171. }
  172. }
  173. $zipFile = $zipDir . '/' . $outputFilename . '.zip';
  174. Log::debug('export chapter start zip file=' . $zipFile);
  175. //zip压缩包里面的文件名
  176. $realFilename = $this->realFilename . "." . $this->format;
  177. $fileContent = Storage::disk('local')->get($filename);
  178. $zipOk = \App\Tools\Tools::zip($zipFile, [$realFilename => $fileContent]);
  179. if (!$zipOk) {
  180. Log::error('export chapter zip fail zip file=' . $zipFile);
  181. $this->setStatus(0.99, 'export chapter zip fail');
  182. $this->error('export chapter zip fail zip file=' . $zipFile);
  183. //TODO 给客户端返回错误状态
  184. return 1;
  185. }
  186. $this->setStatus(0.96, 'export chapter zip success');
  187. $bucket = config('mint.attachments.bucket_name.temporary');
  188. $tmpFile = $bucket . '/' . $this->zipFilename;
  189. Log::debug('upload start filename=' . $tmpFile);
  190. $this->setStatus(0.97, 'upload start ');
  191. $zipData = file_get_contents($zipFile);
  192. Storage::put($tmpFile, $zipData);
  193. if (App::environment('local')) {
  194. $s3Link = Storage::url($tmpFile);
  195. } else {
  196. try {
  197. $s3Link = Storage::temporaryUrl($tmpFile, now()->addDays(7));
  198. } catch (\Exception $e) {
  199. Log::error('export {Exception}', ['exception' => $e]);
  200. return false;
  201. }
  202. }
  203. $this->downloadUrl = $s3Link;
  204. $this->setStatus(1, 'export chapter done');
  205. Log::debug('export chapter done, upload', ['filename' => $tmpFile, 'url' => $s3Link]);
  206. unlink($zipFile);
  207. return true;
  208. }
  209. }