-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.php
182 lines (148 loc) · 4.33 KB
/
index.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
<?php
use GuzzleHttp\Client;
error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(300);
date_default_timezone_set('Europe/Prague');
require_once __DIR__ . '/vendor/autoload.php';
if(is_file(__DIR__ . "/.env")) { // Dev
(new \Dotenv\Dotenv(__DIR__))->load();
}
if(!isset($_GET['token']) || $_GET['token'] !== getenv('SECURITY_TOKEN')) {
http_response_code(401);
echo 'Unauthorized';
exit;
}
$togglToken = getenv('TOGGL_TOKEN');
$togglClientId = getenv('TOGGL_CLIENT_ID');
(new class {
/** @var Client */
private $toggl;
/** @var string */
private $togglClientId;
/** @var Client */
private $jira;
/**
* constructor.
*/
public function __construct()
{
$togglToken = getenv('TOGGL_TOKEN');
$togglClientId = getenv('TOGGL_CLIENT_ID');
$jiraHost = getenv('JIRA_HOST');
$jiraUsername = getenv('JIRA_USERNAME');
$jiraPassword = getenv('JIRA_PASSWORD');
$this->toggl = new Client([
'base_uri' => 'https://www.toggl.com/api/v8/',
'auth' => [$togglToken, 'api_token']
]);
$this->togglClientId = $togglClientId;
$this->jira = new Client([
'base_uri' => $jiraHost.'/rest/api/2/',
'auth' => [$jiraUsername, $jiraPassword],
]);
}
private function getDate(int $daysBack) : string
{
$dt = new DateTime();
if($daysBack > 0) {
$dt->modify('-' . $daysBack . 'days');
}
return $dt->format('c');
}
private function getTogglIssueEntries(int $daysBack)
{
$options = [];
if($daysBack !== 0) {
$options["query"] = [
'start_date' => $this->getDate($daysBack),
'end_date' => $this->getDate($daysBack - 14),
];
}
$body = $this->toggl->get('time_entries', $options)->getBody();
$entries = json_decode($body);
$issueEntries = [];
foreach ($entries as $entry) {
$description = $entry->description ?? '(no description)';
$duration = $entry->duration;
$projectId = $entry->pid ?? NULL;
if ($duration < 0 // Entry still running
|| $projectId === NULL // No project filled
|| !isset($entry->tags) || !in_array('JIRA', $entry->tags) // Only 'JIRA' tagged issues
) { // Different project
continue;
}
preg_match('#(^[A-Z]*-[0-9]*) #', $description, $matches);
if ($matches) {
$issueKey = $matches[1];
$issueEntries[$issueKey] = array_merge($issueEntries[$issueKey] ?? [], [$entry]);
}
}
return $issueEntries;
}
private function logEntries(array $issueEntries)
{
foreach ($issueEntries as $issueKey => $entries) {
try {
$issue = json_decode($this->jira->get("issue/$issueKey/worklog")->getBody());
} catch (\GuzzleHttp\Exception\ClientException $e) {
if ($e->getCode() == 404) {
echo "Issue $issueKey not found.";
continue;
} else {
throw $e;
}
}
$loggedEntries = [];
foreach ($issue->worklogs as $logEntry) {
if (!isset($logEntry->comment)) {
continue; // Skip entries without comment
}
preg_match('/#([0-9]*)/', $logEntry->comment, $matches);
if ($matches) {
$loggedEntries[] = (int)$matches[1];
}
}
foreach ($entries as $entry) {
list($entryId, $duration, $started) = [$entry->id, $entry->duration, $entry->start];
if ($duration < 60) {
echo "Entry below one minute, skipping...<br>";
continue;
}
if (in_array($entryId, $loggedEntries)) {
// Skip already logged entries
echo "Entry #$entryId already logged, skipping...<br>";
continue;
}
$comment = ($entry->description ?? '') . " (Toggl #$entryId)";
$comment = trim($comment);
$this->jira->post('issue/' . $issueKey . '/worklog', [
'json' => [
'timeSpentSeconds' => $duration,
'comment' => $comment,
'started' => DateTime::createFromFormat('Y-m-d\TH:i:sP', $started)->format('Y-m-d\TH:i:s.000O')
]
]);
$host = $this->jira->getConfig('base_uri');
echo "Logged #$entryId in issue <a target='_blank' href='$host/browse/$issueKey'>$issueKey</a>...<br>";
}
}
}
/**
* Sync Toggl entries with JIRA worklogs
* @param string|NULL $errorWebhook
* @param int $daysBack specifies logging interval
* @throws Exception
*/
public function sync(string $errorWebhook, int $daysBack)
{
try {
$this->logEntries($this->getTogglIssueEntries($daysBack));
} catch(\Exception $e) {
if($errorWebhook) {
file_get_contents($errorWebhook);
}
throw $e;
}
}
})->sync(getenv('ERROR_WEBHOOK'), (int) ($_GET['days_back'] ?? 0));