forked from gharlan/alfred-github-workflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workflow.php
367 lines (324 loc) · 12.2 KB
/
workflow.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
<?php
require 'item.php';
require 'curl.php';
class Workflow
{
const VERSION = '$Format:%H$';
const BUNDLE = 'de.gh01.alfred.github';
const DEFAULT_CACHE_MAX_AGE = 10;
private static $filePids;
/** @var PDO */
private static $db;
/** @var PDOStatement[] */
private static $statements = array();
private static $enterprise;
private static $baseUrl = 'https://github.com';
private static $apiUrl = 'https://api.github.com';
private static $gistUrl = 'https://gist.github.com';
private static $query;
private static $items = array();
private static $refreshUrls = array();
public static function init($enterprise = false, $query = null)
{
date_default_timezone_set('UTC');
self::$enterprise = $enterprise;
self::$query = $query;
if (isset($_ENV['alfred_workflow_data'])) {
$dataDir = $_ENV['alfred_workflow_data'];
} else {
$dataDir = (isset($_ENV['HOME']) ? $_ENV['HOME'] : $_SERVER['HOME']) . '/Library/Application Support/Alfred 2/Workflow Data/' . self::BUNDLE;
$_ENV['alfred_workflow_data'] = $dataDir;
}
if (!is_dir($dataDir)) {
mkdir($dataDir);
}
self::$filePids = $dataDir . '/pid';
$fileDb = $dataDir . '/db.sqlite';
$exists = file_exists($fileDb);
self::$db = new PDO('sqlite:' . $fileDb, null, null);
if (!$exists) {
self::$db->exec('
CREATE TABLE config (
key TEXT PRIMARY KEY,
value TEXT
)
');
self::createRequestCacheTable();
}
if (self::$enterprise) {
self::$baseUrl = self::getConfig('enterprise_url');
self::$apiUrl = self::$baseUrl ? self::$baseUrl . '/api/v3' : null;
self::$gistUrl = self::$baseUrl ? self::$baseUrl . '/gist' : null;
}
register_shutdown_function(array(__CLASS__, 'shutdown'));
}
public static function shutdown()
{
if (self::$refreshUrls) {
exec('php action.php "> refresh-cache ' . implode(',', self::$refreshUrls) . '" > /dev/null 2>&1 &');
}
}
public static function setConfig($key, $value)
{
self::getStatement('REPLACE INTO config VALUES(?, ?)')->execute(array($key, $value));
}
public static function getConfig($key, $default = null)
{
$stmt = self::getStatement('SELECT value FROM config WHERE key = ?');
$stmt->execute(array($key));
$value = $stmt->fetchColumn();
return false !== $value ? $value : $default;
}
public static function removeConfig($key)
{
self::getStatement('DELETE FROM config WHERE key = ?')->execute(array($key));
}
public static function getBaseUrl()
{
return self::$baseUrl;
}
public static function getApiUrl()
{
return self::$apiUrl;
}
public static function getGistUrl()
{
return self::$gistUrl;
}
public static function setAccessToken($token)
{
self::setConfig(self::$enterprise ? 'enterprise_access_token' : 'access_token', $token);
}
public static function getAccessToken()
{
return self::getConfig(self::$enterprise ? 'enterprise_access_token' : 'access_token');
}
public static function removeAccessToken()
{
self::removeConfig(self::$enterprise ? 'enterprise_access_token' : 'access_token');
}
public static function request($url, Curl $curl = null, $callback = null)
{
$return = false;
$returnValue = null;
if (!$curl) {
$curl = new Curl();
$return = true;
$callback = function ($content) use (&$returnValue) {
$returnValue = $content;
};
}
$curl->add(new CurlRequest($url, null, function (CurlResponse $response) use ($callback) {
if (is_callable($callback) && isset($response->content)) {
$callback($response->content);
}
}));
if ($return) {
$curl->execute();
}
return $returnValue;
}
/**
* @param string $url
* @param Curl $curl
* @param callable $callback
* @param int $maxAge
* @param bool $refreshInBackground
* @return mixed
*/
public static function requestCache($url, Curl $curl = null, $callback = null, $maxAge = self::DEFAULT_CACHE_MAX_AGE, $refreshInBackground = true)
{
$return = false;
$returnValue = null;
if (!$curl) {
$curl = new Curl();
$return = true;
$callback = function ($content) use (&$returnValue) {
$returnValue = $content;
};
}
$stmt = self::getStatement('SELECT * FROM request_cache WHERE url = ?');
$stmt->execute(array($url));
$stmt->bindColumn('timestamp', $timestamp);
$stmt->bindColumn('etag', $etag);
$stmt->bindColumn('content', $content);
$stmt->bindColumn('refresh', $refresh);
$stmt->fetch(PDO::FETCH_BOUND);
$shouldRefresh = $timestamp < time() - 60 * $maxAge;
$refreshInBackground = $refreshInBackground && !is_null($content);
if ($shouldRefresh && $refreshInBackground && $refresh < time() - 60) {
self::getStatement('UPDATE request_cache SET refresh = ? WHERE url = ?')->execute(array(time(), $url));
self::$refreshUrls[] = $url;
}
if (!$shouldRefresh || $refreshInBackground) {
$content = json_decode($content);
$stmt = self::getStatement('SELECT url, content FROM request_cache WHERE parent = ? ORDER BY `timestamp` DESC');
while ($stmt->execute(array($url)) && $data = $stmt->fetchObject()) {
$content = array_merge($content, json_decode($data->content));
$url = $data->url;
}
if (is_callable($callback)) {
$callback($content);
}
return $returnValue;
}
$responses = array();
$handleResponse = function (CurlResponse $response, $content, $parent = null) use (&$handleResponse, $curl, &$responses, $stmt, $callback) {
$url = $response->request->url;
if ($response && in_array($response->status, array(200, 304))) {
$checkNext = false;
if (304 == $response->status) {
$response->content = $content;
$checkNext = true;
} elseif (false === stripos($response->contentType, 'json')) {
$response->content = json_encode($response->content);
}
$responses[] = $response->content;
Workflow::getStatement('REPLACE INTO request_cache VALUES(?, ?, ?, ?, 0, ?)')
->execute(array($url, time(), $response->etag, $response->content, $parent));
if ($checkNext || $response->link && preg_match('/<(.+)>; rel="next"/U', $response->link, $match)) {
$stmt = Workflow::getStatement('SELECT * FROM request_cache WHERE parent = ?');
$stmt->execute(array($url));
if ($checkNext) {
$stmt->bindColumn('url', $nextUrl);
} else {
$nextUrl = $match[1];
}
$stmt->bindColumn('etag', $etag);
$stmt->bindColumn('content', $content);
$stmt->fetch(PDO::FETCH_BOUND);
if ($nextUrl) {
$curl->add(new CurlRequest($nextUrl, $etag, function (CurlResponse $response) use ($handleResponse, $url, $content) {
$handleResponse($response, $content, $url);
}));
return;
}
} else {
Workflow::getStatement('DELETE FROM request_cache WHERE parent = ?')->execute(array($url));
}
} else {
Workflow::getStatement('DELETE FROM request_cache WHERE url = ?')->execute(array($url));
$url = null;
}
if (is_callable($callback)) {
if (empty($responses)) {
$callback(array());
return;
}
if (1 === count($responses)) {
$callback(json_decode($responses[0]));
return;
}
$callback(array_reduce($responses, function ($content, $response) {
return array_merge($content, json_decode($response));
}, array()));
}
};
$curl->add(new CurlRequest($url, $etag, function (CurlResponse $response) use (&$responses, $handleResponse, $callback, $content) {
$handleResponse($response, $content);
}));
if ($return) {
$curl->execute();
}
return $returnValue;
}
public static function requestApi($url, Curl $curl = null, $callback = null, $maxAge = self::DEFAULT_CACHE_MAX_AGE)
{
$paramStart = false === strpos($url, '?') ? '?' : '&';
$url = self::getApiUrl() . $url . $paramStart . 'per_page=100';
return self::requestCache($url, $curl, $callback, $maxAge);
}
public static function cleanCache()
{
self::$db->exec('DELETE FROM request_cache WHERE timestamp < ' . (time() - 30 * 24 * 60 * 60));
}
public static function deleteCache()
{
self::$db->exec('DELETE FROM request_cache');
}
public static function startServer()
{
if (version_compare(PHP_VERSION, '5.4', '>=')) {
self::stopServer();
shell_exec(sprintf(
'alfred_workflow_data=%s php -d variables_order=EGPCS -S localhost:2233 server.php > /dev/null 2>&1 & echo $! >> %s',
escapeshellarg($_ENV['alfred_workflow_data']),
escapeshellarg(self::$filePids)
));
}
}
public static function stopServer()
{
if (file_exists(self::$filePids)) {
$pids = file(self::$filePids);
foreach ($pids as $pid) {
shell_exec('kill -9 ' . $pid);
}
unlink(self::$filePids);
}
}
public static function checkUpdate()
{
if (self::getConfig('version') !== self::VERSION) {
self::setConfig('version', self::VERSION);
//self::deleteCache();
self::closeCursors();
self::$db->exec('DROP TABLE request_cache');
self::createRequestCacheTable();
}
if (!self::getConfig('autoupdate', 1)) {
return false;
} elseif (!is_dir(__DIR__ . '/icons')) {
return true;
}
$version = self::requestCache('http://gh01.de/alfred/github/current', null, null, 1440);
return $version !== null && $version !== self::VERSION;
}
private static function createRequestCacheTable()
{
self::$db->exec('
CREATE TABLE request_cache (
url TEXT PRIMARY KEY,
timestamp INTEGER,
etag TEXT,
content TEXT,
refresh INTEGER,
parent TEXT
)
');
}
public static function addItem(Item $item, $check = true)
{
if (!$check || $item->match(self::$query)) {
self::$items[] = $item;
}
}
public static function sortItems()
{
usort(self::$items, function (Item $a, Item $b) {
return $a->compare($b);
});
}
public static function getItemsAsXml()
{
return Item::toXml(self::$items, self::$enterprise, self::getBaseUrl());
}
/**
* @param string $query
* @return PDOStatement
*/
public static function getStatement($query)
{
if (!isset(self::$statements[$query])) {
self::$statements[$query] = self::$db->prepare($query);
}
return self::$statements[$query];
}
protected static function closeCursors()
{
foreach (self::$statements as $statement) {
$statement->closeCursor();
}
self::$statements = array();
}
}