file upload support for notes (single + multi)
[shpub.git] / src / shpub / Command / Note.php
1 <?php
2 namespace shpub;
3
4 class Command_Note
5 {
6     /**
7      * @var Config
8      */
9     protected $cfg;
10
11     public function __construct($cfg)
12     {
13         $this->cfg = $cfg;
14     }
15
16     public static function opts(\Console_CommandLine $optParser)
17     {
18         $cmd = $optParser->addCommand('note');
19         $cmd->addOption(
20             'files',
21             array(
22                 'short_name'  => '-f',
23                 'long_name'   => '--files',
24                 'description' => 'Files to upload',
25                 'help_name'   => 'PATH',
26                 'action'      => 'StoreArray',
27                 'default'     => [],
28             )
29         );
30         $cmd->addArgument(
31             'text',
32             [
33                 'optional'    => false,
34                 'multiple'    => false,
35                 'description' => 'Post text',
36             ]
37         );
38     }
39
40     public function run($command)
41     {
42         $req = new Request($this->cfg->host, $this->cfg);
43         $req->req->addPostParameter('h', 'entry');
44         $req->req->addPostParameter('content', $command->args['text']);
45
46         $files = $command->options['files'];
47         $fileList = [
48             'audio' => [],
49             'photo' => [],
50             'video' => [],
51         ];
52         foreach ($files as $filePath) {
53             if (!file_exists($filePath)) {
54                 Log::err('File does not exist: ' . $filePath);
55                 exit(20);
56             }
57             $type = 'photo';
58             $fileList[$type][] = $filePath;
59         }
60         foreach ($fileList as $type => $filePaths) {
61             if (count($filePaths) == 1) {
62                 $req->addUpload($type, reset($filePaths));
63             } else if (count($filePaths) > 0) {
64                 $req->addUpload($type, $filePaths);
65             }
66         }
67
68         $res = $req->send();
69         $postUrl = $res->getHeader('Location');
70         echo "Post created at server\n";
71         echo $postUrl . "\n";
72     }
73 }
74 ?>