-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhttp.php
204 lines (179 loc) · 7.05 KB
/
http.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
<?php
namespace jinni;
/**
* Class for making HTTP interactions with Jinni.
*/
class http {
protected $username;
protected $cacheFolder;
protected $jSessionID;
public function __construct($username, $cacheFolder) {
$this->username = $username;
$this->cacheFolder = rtrim($cacheFolder,'/\\');
}
public function getPage($path, $postData = null, $cache = false, $headersOnly = false) {
if ($cache && ($cachepath = $this->createCachePath($path)) && file_exists($cachepath)) {
return file_get_contents($cachepath);
}
$ch = curl_init('http://www.jinni.com'.$path);
curl_setopt($ch,
CURLOPT_COOKIE,
"auth=".$this->username.
(!empty($this->jSessionID)?';JSESSIONID='.$this->jSessionID:'')
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_ENCODING, "");
if (is_array($postData)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
} elseif (is_string($postData)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$result = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
$headers = substr($result, 0, $info['header_size']);
if (preg_match("@Set-Cookie: JSESSIONID=([^;]+);@i", $headers, $matches)) {
$this->jSessionID = $matches[1];
}
if ($headersOnly) {
$page = $headers;
} else {
$page = substr($result, $info['header_size']);
}
if ($cache) {
file_put_contents($cachepath, $page);
}
return $page;
}
/**
* Create a cache folder for storing the result of getting $path
* @param string $path
* @return string the location to store the result
*/
protected function createCachePath($path) {
$path = trim($path,'/');
$parts = explode('/', $path);
$filename = str_replace(array("\\",'/',':','*','?','"','<','>','|'),'',array_pop($parts));
$filePath = $this->cacheFolder . '/';
while ($thisFolder = array_shift($parts)) {
$filePath .= str_replace(array("\\",'/',':','*','?','"','<','>','|'),'',$thisFolder) . '/';
if (!is_dir($filePath)) {
mkdir($filePath);
}
}
return $filePath . $filename;
}
/**
* Make a call to the DWR API
* @param string $scriptName e.g. AjaxUserRatingBean
* @param string $method e.g. getContentRating
* @param array $params
* @return mixed
* @throws \Exception
*
* **AjaxUserRatingBean**
* getContentRating (filmId) => {likelyOrNotInterested:null,rate:5.0,rated:true,suggested:false}
* submiteContentUserRating (filmId, rating) => "Thank you for rating"
* removeRating (filmId) => null (returns null if it was rated previously or not)
*
* getUserRate => 5.0 //based on last film looked at
* getRatings (broken? returns [null,null,null.....
*
*
* **AjaxController**
* findSuggestionsWithFilters (term,
* {contentTypeFilter:FeatureFilm|TvSeries})=> @see parseSearchSuggestionResults()
*
* **AjaxUserRecommendationsBean**
* getRecommendations Returns tons of data about all your recommended films/shows
*/
public function apiCall($scriptName, $method, array $params = array()) {
$response = $this->rawApiCall($scriptName, $method, $params);
if (0 == preg_match('@dwr.engine._remoteHandleCallback\(\'\d+\',\'\d+\',(.+)\);@', $response, $matches)) {
throw new \Exception('API call failed');
}
if (null === ($return = $this->jsDecode($matches[1]))) {
throw new \Exception('Decoding JSON in API response failed');
}
return $return;
}
/**
*
* @param string $searchStr
* @param string|null $type FeatureFilm|TvSeries|ShortFilm @see film::validContentType()
* @return array()
* @see parseSearchSuggestionResults()
*/
public function searchSuggestions($searchStr, $type = null) {
if (null !== $type && !film::validContentType($type)) {
throw new \Exception('Invalid content type: '.$type);
}
$return = $this->rawApiCall('AjaxController', 'findSuggestionsWithFilters', array($searchStr, (object)array('contentTypeFilter' => $type)));
return $this->parseSearchSuggestionResults($return);
}
protected function rawApiCall($scriptName, $method, array $params = array()) {
if (!$this->jSessionID) {
// API calls need a session ID. Get a lightweight page
$this->getPage('/sitemap.html');
}
$postData = 'callCount=1'."\n".
'batchId=0'."\n".
'httpSessionId='.$this->jSessionID."\n".
'scriptSessionId=3C675DDBB02222BE8CB51E2415259E99676'."\n".
'c0-scriptName='.$scriptName."\n".
'c0-methodName='.$method."\n".
'c0-id=0'."\n";
$postData .= $this->buildApiParamString($params);
return $this->getPage('/dwr/call/plaincall/AjaxUserRatingBean.dwr', $postData);
}
protected function buildApiParamString(array $params) {
$paramStr = '';
$i = 0;
foreach ($params as $param) {
$paramStr .= "c0-param$i=".$this->buildParamVar($param)."\n";
$i++;
}
return $paramStr;
}
protected function buildParamVar($param) {
if (is_int($param)) {
return "number:$param";
}
if (is_object($param)) {
$str = "Object_Object:{";
foreach (get_object_vars($param) as $k => $x) {
$str .= "$k:".$this->buildParamVar($x).',';
}
return rtrim($str,',').'}';
}
if (is_null($param)) {
return "null:null";
}
if (is_string($param)) {
return "string:$param";
}
}
protected function parseSearchSuggestionResults($str) {
if (0 == preg_match("@dwr.engine._remoteHandleCallback\(\'\d+\',\'\d+\',\{results:([^,]+),@", $str, $matches)) {
throw new \Exception('Could not parse API result');
}
preg_match_all("@s\d+.categoryType=null;s\d+.entityType='Title';s\d+.id=\"(\d+)\";s\d+.name=\"([^\"]+)\";s\d+.popularity=null;s\d+.titleType=\'([A-Z,a-z]+)';s\d+.year=(\d+);@", $str, $matches, PREG_SET_ORDER);
$results = array();
foreach ($matches as $match) {
$results[] = array(
'id' => $match[1],
'name' => stripslashes($match[2]),
'year' => $match[4],
'contentType' => $match[3]
);
}
return $results;
}
protected function jsDecode($str) {
$str = preg_replace('@\b([a-z0-9]+)(\s*:)@i', "\"$1\"$2", $str);
return json_decode($str);
}
}