-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.php
104 lines (71 loc) · 2.19 KB
/
app.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
<?php
require './vendor/autoload.php';
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
class App
{
protected $config;
public function __construct(array $config)
{
$this->config = $config;
}
public function run(string $type = '') : void
{
$name = $this->generate($type);
$qiniu = $this->upload($name);
$markdown = $this->toMarkdown($name, $qiniu);
$this->clear($name);
echo $markdown;
}
protected function makeLocalPath(string $name) : string
{
$path = sprintf('%s/%s', rtrim($this->config['tmp_dir'], '/'), $name);
return $path;
}
protected function makeQiniuPath(string $name) : string
{
$path = sprintf('%s/%s', date('Y/md'), $name);
return $path;
}
protected function generate(string $type) : string
{
$pngpaste = '/usr/local/bin/pngpaste';
$pngquant = '/usr/local/bin/pngquant';
$type = $type ?: 'png';
$name = time() . '.' . $type;
$path = $this->makeLocalPath($name);
exec($pngpaste . ' ' . $path);
if ($type === 'png') {
exec($pngquant . ' -f -o ' . $path . ' ' . $path);
}
return $name;
}
protected function upload(string $name) : string
{
$auth = new Auth($this->config['access'], $this->config['secret']);
$token = $auth->uploadToken($this->config['bucket']);
$local = $this->makeLocalPath($name);
$qiniu = $this->makeQiniuPath($name);
[$result, $error] = (new UploadManager)->putFile($token, $qiniu, $local);
if (!empty($error)) {
return $error->message();
}
$url = $this->makeQiniuURL($result['key']);
return $url;
}
protected function makeQiniuURL(string $path) : string
{
$url = rtrim($this->config['domain'], '/') . '/' . $path;
return $url;
}
protected function clear(string $name) : void
{
$path = $this->makeLocalPath($name);
@unlink($path);
}
protected function toMarkdown(string $name, string $url) : string
{
$markdown = sprintf('![%s](%s)', $name, $url);
return $markdown;
}
}