ExportDownload.php 7.7 KB

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