Completed
Push — master ( b991b0...0f93a7 )
by Tyler
10:35 queued 09:22
created

ViddlerClient::getRecordToken()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
ccs 0
cts 5
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 0
crap 6
1
<?php
2
3
namespace LeadThread\Viddler\Upload\Components;
4
5
use Exception;
6
use LeadThread\Viddler\Upload\Traits\CanLog;
7
use LeadThread\Viddler\Api\Exceptions\ViddlerException;
8
use LeadThread\Viddler\Api\Viddler as ViddlerV2;
9
use LeadThread\Viddler\Upload\Models\Viddler;
10
use LeadThread\Viddler\Upload\Events\ViddlerProgress;
11
12
class ViddlerClient
13
{
14
    use CanLog;
15
    
16
    protected $client;
17
    protected $session_id;
18
    protected $record_token;
19
20
    protected function prepareUpload()
21
    {
22
        if (empty($this->session_id)) {
23
            $this->auth();
24
        }
25
26
        return $this->client->viddler_videos_prepareUpload([
27
            'response_type' => 'json',
28
            'sessionid' => $this->session_id
29
        ]);
30
    }
31
32
    protected function executeUpload($endpoint, $postFields)
33
    {
34
        try {
35
            $ch = curl_init();
36
37
            if (false === $ch) {
38
                throw new Exception('failed to initialize');
39
            }
40
41
            curl_setopt($ch, CURLOPT_URL, $endpoint);
42
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
43
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
44
            curl_setopt($ch, CURLOPT_HEADER, true);
45
            curl_setopt($ch, CURLOPT_NOBODY, false);
46
            curl_setopt($ch, CURLOPT_TIMEOUT, 0);
47
            curl_setopt($ch, CURLOPT_POST, true);
48
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
49
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
50
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
51
            $response     = curl_exec($ch);
52
53
            if (false === $response) {
54
                throw new Exception(curl_error($ch), curl_errno($ch));
55
            }
56
57
            $info         = curl_getinfo($ch);
58
            $header_size  = $info['header_size'];
59
            $header       = substr($response, 0, $header_size);
0 ignored issues
show
Unused Code introduced by
$header is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
60
            $result       = unserialize(substr($response, $header_size));
61
            curl_close($ch);
62
        } catch (Exception $e) {
63
            $err = sprintf('Curl failed with error #%d: %s', $e->getCode(), $e->getMessage());
64
            throw new Exception($err);
65
        }
66
67
        return $result;
68
    }
69
70
    protected function executeCheck(Viddler $model)
71
    {
72
        if (empty($this->session_id)) {
73
            $this->auth();
74
        }
75
76
        return $this->client->viddler_encoding_getStatus2([
77
            'video_id' => $model->viddler_id,
78
            'response_type' => 'json',
79
            'sessionid' => $this->session_id
80
        ]);
81
    }
82
83 18
    public function check(Viddler $model)
84
    {
85 6
        if ($model->status === "encoding") {
86 6
            $this->info("{$model} is checking encoding status on viddler.com");
87 6
            $response = $this->executeCheck($model);
88
            
89 6
            $files = collect($response["list_result"]["video_encoding_list"][0]["video_file_encoding_list"]);
90
91 18
            if ($files->count() < 1) {
92
                throw new ViddlerException("No files were returned from viddler");
93
            } else {
94 6
                $progressAll = $files->sum('encoding_progress')/$files->count();
95
96 6
                $files = $files->filter(function ($file) {
97 6
                    return $file["profile_name"] === "360p";
98 6
                });
99
100
                // Status
101 6
                $x = 0;
102 6
                foreach ($files as $file) {
103 6
                    $x += $file['status'] === 'ready' ? 1 : 0;
104 6
                }
105 6
                $status = $x/$files->count() === 1;
106
107
                // Progress percentage
108 6
                $progress360p = $files->sum('encoding_progress')/$files->count();
109 6
                $oldProgress = $model->encoding_progress;
0 ignored issues
show
Documentation introduced by
The property encoding_progress does not exist on object<LeadThread\Viddler\Upload\Models\Viddler>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
110 6
                $model->encoding_progress = round(max($progress360p, $progressAll));
0 ignored issues
show
Documentation introduced by
The property encoding_progress does not exist on object<LeadThread\Viddler\Upload\Models\Viddler>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
111
112
                // Check it
113 6
                if ($model->encoding_progress == 100 && $status) {
0 ignored issues
show
Documentation introduced by
The property encoding_progress does not exist on object<LeadThread\Viddler\Upload\Models\Viddler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
114
                    // This method will save the model
115 6
                    $model->updateStatusTo('finished');
116 3
                } else {
117
                    if ($model->encoding_progress == 100) {
0 ignored issues
show
Documentation introduced by
The property encoding_progress does not exist on object<LeadThread\Viddler\Upload\Models\Viddler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
118
                        $model->encoding_progress = 99;
0 ignored issues
show
Documentation introduced by
The property encoding_progress does not exist on object<LeadThread\Viddler\Upload\Models\Viddler>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
119
                    }
120
                    $model->save();
121
122
                    if ($oldProgress !== $model->encoding_progress) {
0 ignored issues
show
Documentation introduced by
The property encoding_progress does not exist on object<LeadThread\Viddler\Upload\Models\Viddler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
123
                        $this->info("{$model}'s encoding progress: {$model->encoding_progress}");
0 ignored issues
show
Documentation introduced by
The property encoding_progress does not exist on object<LeadThread\Viddler\Upload\Models\Viddler>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
124
                        event(new ViddlerProgress($model));
125
                    }
126
                }
127
            }
128 3
        }
129
130 3
        return $model;
131
    }
132
133 18
    public function upload(Viddler $model)
134
    {
135 18
        $this->info("{$model} is uploading to viddler.com");
136
        //Fire Event
137 18
        $model->updateStatusTo('uploading');
138
139
        //Path
140 18
        $file = $model->getFile();
141 18
        $path = $file->getFullPath();
142
143 18
        $response = $this->prepareUpload();
144
145 15
        $token      = $response['upload']['token'];
146 15
        $endpoint   = $response['upload']['endpoint'];
147
148
        //Prepare the data!
149 15
        $postFields = array();
150 15
        $postFields['description'] = "";
151 15
        $postFields['tags'] = "";
152 15
        $postFields['title'] = $model->title;
153 15
        $postFields['uploadtoken'] = $token;
154 15
        $postFields['view_perm'] = "embed";
155 15
        $postFields['file'] = curl_file_create($path, $model->mime);
156
157
        //Send it!
158 15
        $result = $this->executeUpload($endpoint, $postFields);
159
160 15
        if (empty($result['video']['id'])) {
161
            throw new ViddlerException('Viddler did not return a video id!');
162
        }
163
164 15
        $model->viddler_id = $result['video']['id'];
165 15
        $model->uploaded = true;
166 15
        $model->updateStatusTo('encoding');
167
168 15
        return $model;
169
    }
170
171
    /**
172
     * Authenticate with viddler
173
     */
174
    protected function auth()
175
    {
176
        $key  = config('viddler.auth.key');
177
        $user = config('viddler.auth.user');
178
        $pass = config('viddler.auth.pass');
179
180
        //Create Client
181
        if (empty($this->client)) {
182
            $this->client = new ViddlerV2($key);
183
        }
184
185
        $resp = $this->client->viddler_users_auth(array('user' => $user, 'password' => $pass));
186
187
        $this->session_id = $resp['auth']['sessionid'];
188
        
189
        if (!empty($resp['auth']['record_token'])) {
190
            $this->record_token = $resp['auth']['record_token'];
191
        }
192
    }
193
194
    /**
195
     * Return the session id
196
     */
197
    protected function getSessionId()
198
    {
199
        if (empty($this->session_id)) {
200
            $this->auth();
201
        }
202
        return $this->session_id;
203
    }
204
205
    /**
206
     * Return the record token for this session
207
     */
208
    protected function getRecordToken()
209
    {
210
        if (empty($this->session_id)) {
211
            $this->auth();
212
        }
213
        return $this->record_token;
214
    }
215
}
216