Script to sync Toggl entries with Assembla

См. скрипт под катом.

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
# created at 2015 May - June
# author: <w1ld at inbox ru>
import logging, requests, re, json, datetime, sys, argparse
EPSILON = 0.01
_assemblaSecretHeaders = None
_toggl_user_agent = None
_toggl_workspace_id = None
_toggl_api_token = None
_supposed_number_of_items_in_page_to_find_the_one = 100
_assembla_tasks_of_today = None
_logger = logging.getLogger('simple_example')
ch = logging.StreamHandler()
formatter = logging.Formatter('%(message)s')
ch.setFormatter(formatter)
_logger.addHandler(ch)
def _log_requests_response_hook(r, *args, **kwargs):
_logger.debug(" response\n url: " + r.url)
_requests_hooks = dict(response=_log_requests_response_hook)
def _get_toggl_entries(date, projectNames):
_logger.info('getting toggl entries')
assert(date.isoformat)
assert _toggl_workspace_id
assert _toggl_user_agent
assert _toggl_api_token
params = {
'until' : date.isoformat(),
'since' : date.isoformat(),
'user_agent': _toggl_user_agent,
'workspace_id': _toggl_workspace_id,
'project_ids': ''
}
# https://github.com/toggl/toggl_api_docs/blob/master/reports.md
response = requests.get(
'https://toggl.com/reports/api/v2/summary',
params = params,
auth = (_toggl_api_token, 'api_token'),
hooks = _requests_hooks
)
assert response.status_code == 200
summary = response.json()
assert summary['data'], summary['data']
entries = []
# https://github.com/toggl/toggl_api_docs/blob/master/reports/summary.md#data-array
for project in summary['data']:
name = project['title']['project']
if(name in projectNames):
for item in project['items']:
entries.append(item)
_logger.info('got toggl entries: %d', len(entries))
return entries
def _get_tasks_of_today(spaceId, date):
global _assembla_tasks_of_today
if(not _assembla_tasks_of_today):
_logger.info(' getting today assembla tasks')
assert(date.isoformat)
params = {
'spaces' : [spaceId],
'from' : date.strftime('%Y/%m/%d'),
'per_page' : _supposed_number_of_items_in_page_to_find_the_one
}
# http://api-doc.assembla.com/content/ref/task_fields.html
# http://api-doc.assembla.com/content/ref/tasks_index.html
r = requests.get(
'https://api.assembla.com/v1/tasks.json',
headers = _assemblaSecretHeaders,
params = params,
hooks = _requests_hooks)
if(r.status_code == 204):
return []
assert(r.status_code == 200)
_assembla_tasks_of_today = r.json()
_logger.info(' got assembla tasks: %d', len(_assembla_tasks_of_today))
return _assembla_tasks_of_today
def _sync_ticket(spaceId, togglEntry, date):
assert spaceId
assert togglEntry
assert date
assert togglEntry['title']
timeEntry = togglEntry['title'][ 'time_entry' ]
timeEntry = timeEntry.strip()
assert timeEntry
ticketNumber = _extract_ticket_number(timeEntry)
assert ticketNumber
matchingTicket = _find_matching_ticket(spaceId, ticketNumber)
assert matchingTicket
ticketId = matchingTicket['id']
assert ticketId
entryMilliseconds = togglEntry['time']
hours = entryMilliseconds / 1000.0 / 60.0 / 60.0
assert(hours >= 0.0)
_logger.info('syncing "%s" (%f hrs) toggl entry', timeEntry, hours)
foundTasks = _get_tasks_of_today(spaceId, date)
is_there_already_time_entry = False
for userTask in foundTasks:
taskHours = float(userTask['hours'])
assert(taskHours)
if(userTask['ticket_id'] == ticketId and abs(taskHours - hours) < EPSILON):
is_there_already_time_entry = True
isAssemblaTaskCreated = False
if(not is_there_already_time_entry):
_logger.info(' posting task %s, %d to assembla', timeEntry, hours)
form = { 'user_task': {
'space_id' : spaceId,
'description' : timeEntry,
'begin_at' : date.isoformat(),
'end_at' : date.isoformat(),
'hours' : hours,
'ticket_id' : matchingTicket['id'],
}
}
jsonDumps = json.dumps(form)
_logger.info(' jsonForm = ' + jsonDumps)
# http://api-doc.assembla.com/content/ref/tasks_create.html
r = requests.post(
'https://api.assembla.com/v1/tasks',
json = form,
hooks = _requests_hooks,
headers = _assemblaSecretHeaders
)
assert(r.status_code == 201)
_logger.info(' task posted')
isAssemblaTaskCreated = True
return isAssemblaTaskCreated
def _extract_ticket_number(timeEntry):
assert(timeEntry)
match = re.match('\s*\#\s*(\d+)', timeEntry)
if(match):
return int(match.group(1))
return None
def _find_matching_ticket(spaceId, ticketNumber):
_logger.info(' finding matching ticket')
assert(spaceId)
assert(ticketNumber)
# http://api-doc.assembla.com/content/ref/tickets_show.html
r = requests.get(
'https://api.assembla.com/v1/spaces/' + spaceId + '/tickets/' + str(ticketNumber) + '.json',
headers = _assemblaSecretHeaders,
hooks = _requests_hooks
)
assert(r.status_code == 200)
ticket = r.json()
assert(ticket['number'] == ticketNumber)
_logger.info(' found matching ticket: %s', ticketNumber)
return ticket
def _get_assembla_space_id(spaceName):
_logger.info('getting assembla space id')
r = requests.get(
'https://api.assembla.com/v1/spaces',
headers = _assemblaSecretHeaders,
hooks = _requests_hooks)
assert(r.status_code == 200)
spaces = r.json()
for space in spaces:
if(space['name'] == spaceName):
spaceId = space['id']
_logger.info('got assembla space id: %s', spaceId)
return spaceId
raise Error('Unknown space')
def sync(date, projectNames, spaceName):
_logger.info('syncing %s date in %s space for %s projects', date.strftime('%Y-%m-%d'), spaceName, projectNames)
togglEntries = _get_toggl_entries(date, projectNames)
spaceId = _get_assembla_space_id(spaceName)
count = 0
for togglEntry in togglEntries :
isPosted = _sync_ticket(spaceId, togglEntry, date)
if isPosted: count += 1
_logger.info('syncing finished: %d posted to assembla', count)
if(__name__ == '__main__'):
parser = argparse.ArgumentParser( description='Sync toggl with assembla', usage='%(prog)s [OPTIONS]')
parser.add_argument('--assembla-x-api-key', help='assembla x-api-key', required=True)
parser.add_argument('--assembla-x-api-secret', help='assembla x-api-secret', required=True)
parser.add_argument('--toggl-user-name', help='toggl user name (email)', required=True)
parser.add_argument('--toggl-workspace-id', help='toggl workspace id', required=True)
parser.add_argument('--toggl-api-token', help='toggl api token', required=True)
parser.add_argument('--toggl-project-names',
help='Toggl project names', metavar='NAME', nargs='+', required=True)
parser.add_argument('--assembla-space-name', required=True)
parser.add_argument('--date', help='date to sync (yyyy-mm-dd)')
args = parser.parse_args()
date = (datetime.datetime.strptime(args.date, '%Y-%m-%d') if(args.date) else datetime.date.today())
_logger.setLevel(logging.INFO)
_assemblaSecretHeaders = {
'X-Api-Key': args.assembla_x_api_key,
'X-Api-Secret': args.assembla_x_api_secret
}
_toggl_user_agent = args.toggl_user_name
_toggl_workspace_id = args.toggl_workspace_id
_toggl_api_token = args.toggl_api_token
projectNames = args.toggl_project_names
assembla_space_name = args.assembla_space_name
_logger.info('starting')
sync(date, projectNames, assembla_space_name)
# The MIT License (MIT)
#
# Copyright (c) 2015 w1ld at inbox ru
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.