Completed
Push — master ( 22776c...03dd5a )
by Sergey
03:25
created

Request   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 235
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 1 Features 0
Metric Value
wmc 21
c 2
b 1
f 0
lcom 1
cbo 3
dl 0
loc 235
rs 10

13 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A followMethodCall() 0 18 2
A checkLoggedIn() 0 8 2
A exec() 0 12 1
A makeHttpOptions() 0 15 3
A clearToken() 0 4 1
A setLoggedIn() 0 7 2
A isLoggedIn() 0 5 1
A createRequestData() 0 17 3
A createEmptyRequestData() 0 4 1
A getDefaultHttpOptions() 0 16 1
A getDefaultHttpHeaders() 0 4 1
A addDefaultCsrfInfo() 0 7 1
1
<?php
2
3
namespace seregazhuk\PinterestBot\Api;
4
5
use seregazhuk\PinterestBot\Helpers\UrlHelper;
6
use seregazhuk\PinterestBot\Helpers\CsrfHelper;
7
use seregazhuk\PinterestBot\Interfaces\HttpInterface;
8
use seregazhuk\PinterestBot\Interfaces\RequestInterface;
9
10
/**
11
 * Class Request
12
 *
13
 * @package Pinterest
14
 * @property resource $ch
15
 * @property bool     $loggedIn
16
 * @property string   $userAgent
17
 * @property string   $csrfToken
18
 * @property string   $cookieJar
19
 */
20
class Request implements RequestInterface
21
{
22
    const INTEREST_ENTITY_ID = 'interest_id';
23
    const BOARD_ENTITY_ID    = 'board_id';
24
    const PINNER_ENTITY_ID   = 'user_id';
25
26
    protected $userAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0';
27
    const COOKIE_NAME = 'pinterest_cookie';
28
    /**
29
     * @var HttpInterface
30
     */
31
    protected $http;
32
    protected $loggedIn;
33
    protected $cookieJar;
34
35
    public    $csrfToken = "";
36
37
    /**
38
     * Common headers needed for every query
39
     *
40
     * @var array
41
     */
42
    protected $requestHeaders = [
43
        'Host: www.pinterest.com',
44
        'Accept: application/json, text/javascript, */*; q=0.01',
45
        'Accept-Language: en-US,en;q=0.5',
46
        'DNT: 1',
47
        'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
48
        'X-Pinterest-AppState: active',
49
        'X-NEW-APP: 1',
50
        'X-APP-VERSION: 04cf8cc',
51
        'X-Requested-With: XMLHttpRequest',
52
    ];
53
54
    /**
55
     * @param HttpInterface $http
56
     */
57
    public function __construct(HttpInterface $http)
58
    {
59
        $this->http = $http;
60
        $this->cookieJar = self::COOKIE_NAME;
61
62
        if (file_exists($this->cookieJar)) {
63
            $this->setLoggedIn();
64
        }
65
    }
66
67
    /**
68
     * Executes api call for follow or unfollow user
69
     *
70
     * @param int    $entityId
71
     * @param string $entityName
72
     * @param string $url
73
     * @return array
74
     */
75
    public function followMethodCall($entityId, $entityName, $url)
76
    {
77
        $dataJson = [
78
            "options" => [
79
                $entityName => $entityId,
80
            ],
81
            "context" => [],
82
        ];
83
84
        if ($entityName == self::INTEREST_ENTITY_ID) {
85
            $dataJson["options"]["interest_list"] = "favorited";
86
        }
87
88
        $post = ["data" => json_encode($dataJson, JSON_FORCE_OBJECT)];
89
        $postString = UrlHelper::buildRequestString($post);
90
91
        return $this->exec($url, $postString);
92
    }
93
94
    /**
95
     * Checks if bot is logged in
96
     *
97
     * @throws \LogicException if is not logged in
98
     * @return bool
99
     */
100
    public function checkLoggedIn()
101
    {
102
        if ( ! $this->loggedIn) {
103
            throw new \LogicException("You must log in before.");
104
        }
105
106
        return true;
107
    }
108
109
    /**
110
     * Executes request to Pinterest API
111
     *
112
     * @param string $resourceUrl
113
     * @param string $postString
114
     * @return array
115
     */
116
    public function exec($resourceUrl, $postString = "")
117
    {
118
        $url = UrlHelper::buildApiUrl($resourceUrl);
119
        $options = $this->makeHttpOptions($postString);
120
        $this->http->init($url);
121
        $this->http->setOptions($options);
122
123
        $res = $this->http->execute();
124
        $this->http->close();
125
126
        return json_decode($res, true);
127
    }
128
129
    /**
130
     * Adds necessary curl options for query
131
     *
132
     * @param string $postString POST query string
133
     * @return array
134
     */
135
    protected function makeHttpOptions($postString = "")
136
    {
137
        $options = $this->getDefaultHttpOptions();
138
139
        if ($this->csrfToken == CsrfHelper::DEFAULT_TOKEN) {
140
            $options = $this->addDefaultCsrfInfo($options);
141
        }
142
143
        if ( ! empty($postString)) {
144
            $options[CURLOPT_POST] = true;
145
            $options[CURLOPT_POSTFIELDS] = $postString;
146
        }
147
148
        return $options;
149
    }
150
151
    /**
152
     * Clear token information
153
     *
154
     * @return mixed
155
     */
156
    public function clearToken()
157
    {
158
        $this->csrfToken = CsrfHelper::DEFAULT_TOKEN;
159
    }
160
161
    /**
162
     * Mark api as logged
163
     */
164
    public function setLoggedIn()
165
    {
166
        $this->csrfToken = CsrfHelper::getTokenFromFile($this->cookieJar);
167
        if ( ! empty($this->csrfToken)) {
168
            $this->loggedIn = true;
169
        }
170
    }
171
172
    /**
173
     * Get log status
174
     *
175
     * @return bool
176
     */
177
    public function isLoggedIn()
178
    {
179
        echo "triger\n";
180
        return $this->loggedIn;
181
    }
182
183
    /**
184
     * @param array|object $data
185
     * @param string|null  $sourceUrl
186
     * @param array        $bookmarks
187
     * @return array
188
     */
189
    public static function createRequestData($data = [], $sourceUrl = '/', $bookmarks = [])
190
    {
191
        if (empty($data)) {
192
            $data = self::createEmptyRequestData();
193
        }
194
195
        if ( ! empty($bookmarks)) {
196
            $data["options"]["bookmarks"] = $bookmarks;
197
        }
198
199
        $data["context"] = new \stdClass();
200
201
        return [
202
            "source_url" => $sourceUrl,
203
            "data"       => json_encode($data),
204
        ];
205
    }
206
207
    /**
208
     * @return array
209
     */
210
    protected static function createEmptyRequestData()
211
    {
212
        return array('options' => []);
213
    }
214
215
    /**
216
     * @return array
217
     */
218
    protected function getDefaultHttpOptions()
219
    {
220
        $options = [
221
            CURLOPT_USERAGENT      => $this->userAgent,
222
            CURLOPT_RETURNTRANSFER => true,
223
            CURLOPT_SSL_VERIFYPEER => false,
224
            CURLOPT_FOLLOWLOCATION => true,
225
            CURLOPT_ENCODING       => 'gzip,deflate',
226
            CURLOPT_HTTPHEADER     => $this->getDefaultHttpHeaders(),
227
            CURLOPT_REFERER        => UrlHelper::URL_BASE,
228
            CURLOPT_COOKIEFILE     => $this->cookieJar,
229
            CURLOPT_COOKIEJAR      => $this->cookieJar,
230
        ];
231
232
        return $options;
233
    }
234
235
    /**
236
     * @return array
237
     */
238
    protected function getDefaultHttpHeaders()
239
    {
240
        return array_merge($this->requestHeaders, ['X-CSRFToken: '.$this->csrfToken]);
241
    }
242
243
    /**
244
     * @param $options
245
     * @return mixed
246
     */
247
    protected function addDefaultCsrfInfo($options)
248
    {
249
        $options[CURLOPT_REFERER] = UrlHelper::LOGIN_REF_URL;
250
        $options[CURLOPT_HTTPHEADER][] = CsrfHelper::getDefaultCookie();
251
252
        return $options;
253
    }
254
}
255