1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | querystring = require 'querystring'
|
19 | moment = require 'moment'
|
20 | Promise = require 'bluebird'
|
21 |
|
22 | class Phabricator
|
23 |
|
24 | statuses: {
|
25 | 'open': 'open',
|
26 | 'opened': 'open',
|
27 | 'resolved': 'resolved',
|
28 | 'resolve': 'resolved',
|
29 | 'closed': 'resolved',
|
30 | 'close': 'resolved',
|
31 | 'wontfix': 'wontfix',
|
32 | 'noway': 'wontfix',
|
33 | 'invalid': 'invalid',
|
34 | 'rejected': 'invalid',
|
35 | 'spite': 'spite',
|
36 | 'lame': 'spite'
|
37 | }
|
38 |
|
39 | priorities: {
|
40 | 'unbreak': 100,
|
41 | 'broken': 100,
|
42 | 'triage': 90,
|
43 | 'none': 90,
|
44 | 'unknown': 90,
|
45 | 'low': 25,
|
46 | 'normal': 50,
|
47 | 'high': 80,
|
48 | 'important': 80,
|
49 | 'urgent': 80,
|
50 | 'wish': 0
|
51 | }
|
52 |
|
53 | itemTypes: [
|
54 | 'T',
|
55 | 'F',
|
56 | 'P',
|
57 | 'M',
|
58 | 'B',
|
59 | 'Q',
|
60 | 'L',
|
61 | 'V',
|
62 | 'D'
|
63 | ]
|
64 |
|
65 | constructor: (@robot, env) ->
|
66 | storageLoaded = =>
|
67 | @data = @robot.brain.data.phabricator ||= {
|
68 | projects: { },
|
69 | aliases: { },
|
70 | templates: { },
|
71 | blacklist: [ ],
|
72 | users: { },
|
73 | bot_phid: env.PHABRICATOR_BOT_PHID
|
74 | }
|
75 | @data.templates ?= { }
|
76 | @data.blacklist ?= [ ]
|
77 | @data.users ?= { }
|
78 | @data.alerts ?= { }
|
79 | @data.projects['*'] ?= { }
|
80 | @robot.logger.debug '---- Phabricator Data Loaded.'
|
81 | @robot.brain.on 'loaded', storageLoaded
|
82 | storageLoaded()
|
83 |
|
84 | ready: ->
|
85 | if not process.env.PHABRICATOR_URL
|
86 | @robot.logger.error 'Error: Phabricator url is not specified'
|
87 | if not process.env.PHABRICATOR_API_KEY
|
88 | @robot.logger.error 'Error: Phabricator api key is not specified'
|
89 | unless (process.env.PHABRICATOR_URL? and process.env.PHABRICATOR_API_KEY?)
|
90 | return false
|
91 | true
|
92 |
|
93 | enabledItemsRegex: ->
|
94 | if process.env.PHABRICATOR_ENABLED_ITEMS?
|
95 | r = ''
|
96 | i = []
|
97 | for item in process.env.PHABRICATOR_ENABLED_ITEMS.split(',')
|
98 | if item is 'r'
|
99 | r = '|(r[A-Z]+[a-f0-9]{10,})'
|
100 | else if item in @itemTypes
|
101 | i.push item
|
102 | if i.length > 0
|
103 | '(?:(' + i.join('|') + ')([0-9]+)' + r + ')'
|
104 | else
|
105 | false
|
106 | else
|
107 | '(?:(' + @itemTypes.join('|') + ')([0-9]+)|(r[A-Z]+[a-f0-9]{10,}))'
|
108 |
|
109 | request: (query, endpoint) =>
|
110 | return new Promise (res, err) =>
|
111 | query['api.token'] = process.env.PHABRICATOR_API_KEY
|
112 | body = querystring.stringify(query)
|
113 |
|
114 | @robot.http(process.env.PHABRICATOR_URL)
|
115 | .path("api/#{endpoint}")
|
116 | .get(body) (error, result, payload) ->
|
117 | if result?
|
118 | switch result.statusCode
|
119 | when 200
|
120 | if result.headers['content-type'] is 'application/json'
|
121 | json = JSON.parse(payload)
|
122 | if json.error_info?
|
123 | err json.error_info
|
124 | else
|
125 | res json
|
126 | else
|
127 | err 'api did not deliver json'
|
128 | else
|
129 | err "http error #{result.statusCode}"
|
130 | else
|
131 | err "#{error.code} #{error.message}"
|
132 |
|
133 |
|
134 | isBlacklisted: (id) ->
|
135 | @data.blacklist.indexOf(id) > -1
|
136 |
|
137 | blacklist: (id) ->
|
138 | unless @isBlacklisted(id)
|
139 | @data.blacklist.push id
|
140 |
|
141 | unblacklist: (id) ->
|
142 | if @isBlacklisted(id)
|
143 | pos = @data.blacklist.indexOf id
|
144 | @data.blacklist.splice(pos, 1)
|
145 |
|
146 | getBotPHID: =>
|
147 | return new Promise (res, err) =>
|
148 | if @data.bot_phid?
|
149 | res @data.bot_phid
|
150 | else
|
151 | @request({ }, 'user.whoami')
|
152 | .then (body) =>
|
153 | @data.bot_phid = body.result.phid
|
154 | res @data.bot_phid
|
155 | .catch (e) ->
|
156 | err e
|
157 |
|
158 | getPHID: (phid) =>
|
159 | return new Promise (res, err) =>
|
160 | query = {
|
161 | 'phids[0]': phid
|
162 | }
|
163 | @request(query, 'phid.query')
|
164 | .then (body) ->
|
165 | if body.result[phid]?
|
166 | res body.result[phid]
|
167 | else
|
168 | err 'PHID not found.'
|
169 | .catch (e) ->
|
170 | err e
|
171 |
|
172 | getFeed: (payload) =>
|
173 | return new Promise (res, err) =>
|
174 | data = @data
|
175 | if process.env.PHABRICATOR_FEED_EVERYTHING? and
|
176 | process.env.PHABRICATOR_FEED_EVERYTHING isnt '0' and
|
177 | data.projects['*']?
|
178 | announces = { message: payload.storyText }
|
179 | announces.rooms = []
|
180 | for room in data.projects['*'].feeds
|
181 | if announces.rooms.indexOf(room) is -1
|
182 | announces.rooms.push room
|
183 | res announces
|
184 | else if /^PHID-TASK-/.test payload.storyData.objectPHID
|
185 | query = {
|
186 | 'constraints[phids][0]': payload.storyData.objectPHID,
|
187 | 'attachments[projects]': 1,
|
188 | 'attachments[subscribers]': 1
|
189 | }
|
190 | @request(query, 'maniphest.search')
|
191 | .then (body) ->
|
192 | announces = { message: payload.storyText }
|
193 | announces.rooms = []
|
194 | announces.users = []
|
195 | if body.result.data?
|
196 | for phid in body.result.data[0].attachments.projects.projectPHIDs
|
197 | for name, project of data.projects
|
198 | if name is '*' or
|
199 | (project.phid? and phid is project.phid)
|
200 | project.feeds ?= [ ]
|
201 | if project.parent?
|
202 | data.projects[project.parent].feeds ?= [ ]
|
203 | project.feeds = project.feeds.concat(data.projects[project.parent].feeds)
|
204 | for room in project.feeds
|
205 | if announces.rooms.indexOf(room) is -1
|
206 | announces.rooms.push room
|
207 | for username, userphid of data.alerts
|
208 | if body.result.data[0].fields.ownerPHID is userphid
|
209 | if announces.users.indexOf(username) is -1
|
210 | announces.users.push username
|
211 | for phid in body.result.data[0].attachments.subscribers.subscriberPHIDs
|
212 | if userphid is phid
|
213 | if announces.users.indexOf(username) is -1
|
214 | announces.users.push username
|
215 | res announces
|
216 | .catch (e) ->
|
217 | err e
|
218 | else
|
219 | err 'no room to announce in'
|
220 |
|
221 | getProject: (project, refresh = false) ->
|
222 | if /^PHID-PROJ-/.test project
|
223 | @getProjectByPhid project, refresh
|
224 | else
|
225 | @getProjectByName project, refresh
|
226 |
|
227 | getProjectByPhid: (project, refresh) ->
|
228 | for name, data of @data.projects
|
229 | if data.phid is project
|
230 | projectData = data
|
231 | break
|
232 | if projectData? and not refresh
|
233 | return new Promise (res, err) =>
|
234 | res { aliases: @projectAliases(projectData.name), data: projectData }
|
235 | else
|
236 | @getProjectData project
|
237 |
|
238 | getProjectByName: (project, refresh) ->
|
239 | if @data.projects[project]?
|
240 | projectData = @data.projects[project]
|
241 | else
|
242 | for a, p of @data.aliases
|
243 | if a is project and @data.projects[p]?
|
244 | projectData = @data.projects[p]
|
245 | project = projectData.name
|
246 | break
|
247 | if projectData? and not refresh
|
248 | return new Promise (res, err) =>
|
249 | projectname = projectData.name
|
250 | if projectData.parent?
|
251 | projectname = projectData.parent + '/' + projectname
|
252 | res { aliases: @projectAliases(projectname), data: projectData }
|
253 | else
|
254 | @getProjectData project
|
255 |
|
256 | getProjectData: (project) ->
|
257 | data = @data
|
258 | projectname = null
|
259 | @searchProject(project)
|
260 | .then (projectinfo) =>
|
261 | projectname = projectinfo.name
|
262 | if projectinfo.parent?
|
263 | projectname = projectinfo.parent + '/' + projectname
|
264 | data.projects[projectname] = projectinfo
|
265 | if @aliasize(projectname) isnt projectname
|
266 | data.aliases[@aliasize(projectname)] = projectname
|
267 | @getColumns(projectinfo.phid)
|
268 | .then (columns) =>
|
269 | data.projects[projectname].columns = columns
|
270 | { aliases: @projectAliases(projectname), data: data.projects[projectname] }
|
271 |
|
272 | projectAliases: (project) ->
|
273 | aliases = []
|
274 | for a, p of @data.aliases
|
275 | if p is project
|
276 | aliases.push a
|
277 | aliases
|
278 |
|
279 | aliasize: (str) ->
|
280 | str.trim().toLowerCase().replace(/[^-_a-z0-9]/g, '_')
|
281 |
|
282 | searchProject: (project) ->
|
283 | return new Promise (res, err) =>
|
284 | if /^PHID-PROJ-/.test project
|
285 | query = { 'constraints[phids][0]': project }
|
286 | else
|
287 | if /\//.test project
|
288 | [ parent, project ] = project.split(/\s*\/\s*/)
|
289 | parent_phid = undefined
|
290 | if @data.projects[parent]?
|
291 | parent_phid = @data.projects[parent].phid
|
292 | else
|
293 | for a, p of @data.aliases
|
294 | if a is parent and @data.projects[p]?
|
295 | parent_phid = @data.projects[p].phid
|
296 | break
|
297 | if parent_phid?
|
298 | query = {
|
299 | 'constraints[name]': project,
|
300 | 'constraints[parents][0]': parent_phid
|
301 | }
|
302 | else
|
303 | err "Parent project #{parent} not found. Please .phad info #{parent}"
|
304 | else
|
305 | query = { 'constraints[name]': project }
|
306 | @request(query, 'project.search')
|
307 | .then (body) =>
|
308 | data = body.result.data
|
309 | if data.length > 0
|
310 | found = null
|
311 | for proj in data
|
312 | if /^PHID-PROJ-/.test(project) and proj.phid is project or
|
313 | @aliasize(proj.fields.name) is @aliasize(project)
|
314 | found = proj
|
315 | break
|
316 | if found?
|
317 | phid = found.phid
|
318 | name = found.fields.name.trim()
|
319 | if found.fields.parent?
|
320 | parent = found.fields.parent.name.trim()
|
321 | else
|
322 | parent = null
|
323 | res { name: name, phid: phid, parent: parent }
|
324 | else
|
325 | err "Sorry, tag '#{project}' not found."
|
326 | else
|
327 | err "Sorry, tag '#{project}' not found."
|
328 | .catch (e) ->
|
329 | err e
|
330 |
|
331 | getColumns: (phid) ->
|
332 | query = {
|
333 | 'projectPHIDs[0]': "#{phid}",
|
334 | 'status': 'status-any',
|
335 | 'order': 'order-modified'
|
336 | }
|
337 | @request(query, 'maniphest.query')
|
338 | .then (body) =>
|
339 | query = { 'ids[]': [ ] }
|
340 | for k, i of body.result
|
341 | query['ids[]'].push i.id
|
342 | if query['ids[]'].length is 0
|
343 | @robot.logger.warning "Sorry, we can't find columns for #{phid} " +
|
344 | 'until there are tasks created.'
|
345 | { result: { } }
|
346 | else
|
347 | @request(query, 'maniphest.gettasktransactions')
|
348 | .then (body) =>
|
349 | columns = [ ]
|
350 | for id, o of body.result
|
351 | ts = o.filter (trans) ->
|
352 | trans.transactionType is 'core:columns' and
|
353 | trans.newValue[0].boardPHID is phid
|
354 | boardIds = (t.newValue[0].columnPHID for t in ts)
|
355 | columns = columns.concat boardIds
|
356 | columns = columns.filter (value, index, self) ->
|
357 | self.indexOf(value) is index
|
358 | if columns.length is 0
|
359 | @robot.logger.warning 'Sorry, the tasks in project ' + phid +
|
360 | ' have to be moved around' +
|
361 | ' before we can get the columns.'
|
362 | { result: { } }
|
363 | else
|
364 | query = { 'names[]': columns }
|
365 | @request(query, 'phid.lookup')
|
366 | .then (body) =>
|
367 | back = { }
|
368 | for p, v of body.result
|
369 | name = @aliasize(v.name)
|
370 | back[name] = p
|
371 | back
|
372 |
|
373 | getUser: (from, user) =>
|
374 | return new Promise (res, err) =>
|
375 | if user.name is 'me'
|
376 | user = from
|
377 | unless user.id?
|
378 | user.id = user.name
|
379 | if @data.users[user.id]?.phid?
|
380 | res @data.users[user.id].phid
|
381 | else
|
382 | @data.users[user.id] ?= {
|
383 | name: user.name,
|
384 | id: user.id
|
385 | }
|
386 | if user.phid?
|
387 | @data.users[user.id].phid = user.phid
|
388 | res @data.users[user.id].phid
|
389 | else
|
390 | email = user.email_address or
|
391 | @data.users[user.id].email_address or
|
392 | @robot.brain.userForId(user.id)?.email_address
|
393 | unless email
|
394 | err @_ask_for_email(from, user)
|
395 | else
|
396 | user = @data.users[user.id]
|
397 | query = { 'emails[0]': email }
|
398 | @request(query, 'user.query')
|
399 | .then (body) ->
|
400 | if body.result['0']?
|
401 | user.phid = body['result']['0']['phid']
|
402 | res user.phid
|
403 | else
|
404 | err "Sorry, I cannot find #{email} :("
|
405 |
|
406 | _ask_for_email: (from, user) ->
|
407 | if from.name is user.name
|
408 | "Sorry, I can't figure out your email address :( " +
|
409 | 'Can you tell me with `.phab me as <email>`?'
|
410 | else
|
411 | if @robot.auth? and (@robot.auth.hasRole(from, ['phadmin']) or
|
412 | @robot.auth.isAdmin(from))
|
413 | "Sorry, I can't figure #{user.name} email address. " +
|
414 | "Can you help me with `.phab user #{user.name} = <email>`?"
|
415 | else
|
416 | "Sorry, I can't figure #{user.name} email address. " +
|
417 | 'Can you ask them to `.phab me as <email>`?'
|
418 |
|
419 | recordId: (user, id) ->
|
420 | @data.users[user.id] ?= {
|
421 | name: "#{user.name}",
|
422 | id: "#{user.id}"
|
423 | }
|
424 | @data.users[user.id].lastTask = moment().utc().format()
|
425 | @data.users[user.id].lastId = id
|
426 |
|
427 | getId: (user, id = null) ->
|
428 | return new Promise (res, err) =>
|
429 | @data.users[user.id] ?= {
|
430 | name: "#{user.name}",
|
431 | id: "#{user.id}"
|
432 | }
|
433 | user = @data.users[user.id]
|
434 | if id?
|
435 | if id is 'last'
|
436 | if user? and user.lastId?
|
437 | res user.lastId
|
438 | else
|
439 | err "Sorry, you don't have any task active."
|
440 | else
|
441 | @recordId user, id
|
442 | res id
|
443 | else
|
444 | if user.lastId? and process.env.PHABRICATOR_LAST_TASK_LIFETIME is '-'
|
445 | res user.lastId
|
446 | else
|
447 | user.lastTask ?= moment().utc().format()
|
448 | lifetime = process.env.PHABRICATOR_LAST_TASK_LIFETIME or 60
|
449 | expires_at = moment(user.lastTask).add(lifetime, 'minutes')
|
450 | if user.lastId? and moment().utc().isBefore(expires_at)
|
451 | user.lastTask = moment().utc().format()
|
452 | res user.lastId
|
453 | else
|
454 | err "Sorry, you don't have any task active right now."
|
455 |
|
456 | getUserByPhid: (phid) ->
|
457 | return new Promise (res, err) =>
|
458 | if phid?
|
459 | query = { 'phids[0]': phid }
|
460 | @request(query, 'user.query')
|
461 | .then (body) ->
|
462 | if body['result']['0']?
|
463 | res body['result']['0']['userName']
|
464 | else
|
465 | res 'unknown'
|
466 | .catch (e) ->
|
467 | err e
|
468 | else
|
469 | res 'nobody'
|
470 |
|
471 | getPermission: (user, group) =>
|
472 | return new Promise (res, err) =>
|
473 | if group is 'phuser' and process.env.PHABRICATOR_TRUSTED_USERS is 'y'
|
474 | isAuthorized = true
|
475 | else
|
476 | isAuthorized = @robot.auth?.hasRole(user, [group, 'phadmin']) or
|
477 | @robot.auth?.isAdmin(user)
|
478 | if @robot.auth? and not isAuthorized
|
479 | err "You don't have permission to do that."
|
480 | else
|
481 | res()
|
482 |
|
483 |
|
484 | setAlerts: (username, userPhid) ->
|
485 | return new Promise (res, err) =>
|
486 | if @data.alerts[username]?
|
487 | err 'This alert is already set.'
|
488 | else
|
489 | @data.alerts[username] = userPhid
|
490 | res()
|
491 |
|
492 | unsetAlerts: (username) ->
|
493 | return new Promise (res, err) =>
|
494 | if @data.alerts[username]?
|
495 | delete @data.alerts[username]
|
496 | res()
|
497 | else
|
498 | err 'This alert is not set yet.'
|
499 |
|
500 | taskInfo: (id) ->
|
501 | query = { 'task_id': id }
|
502 | @request query, 'maniphest.info'
|
503 |
|
504 | getTask: (id) ->
|
505 | query = { 'task_id': id }
|
506 | @request query, 'maniphest.info'
|
507 |
|
508 | fileInfo: (id) ->
|
509 | query = { 'id': id }
|
510 | @request query, 'file.info'
|
511 |
|
512 | pasteInfo: (id) ->
|
513 | query = { 'ids[0]': id }
|
514 | @request query, 'paste.query'
|
515 |
|
516 | genericInfo: (name) ->
|
517 | query = { 'names[]': name }
|
518 | @request query, 'phid.lookup'
|
519 |
|
520 | searchTask: (phid, terms, status = undefined, limit = 3) ->
|
521 | query = {
|
522 | 'constraints[fulltext]': terms.replace(' ', '+'),
|
523 | 'constraints[projects][0]': phid,
|
524 | 'order': 'newest',
|
525 | 'limit': limit
|
526 | }
|
527 | if status?
|
528 | query['constraints[statuses][0]'] = status
|
529 | @request query, 'maniphest.search'
|
530 |
|
531 | searchAllTask: (terms, status = undefined, limit = 3) ->
|
532 | query = {
|
533 | 'constraints[fulltext]': terms.replace(' ', '+'),
|
534 | 'order': 'newest',
|
535 | 'limit': limit
|
536 | }
|
537 | if status?
|
538 | query['constraints[statuses][0]'] = status
|
539 | @request query, 'maniphest.search'
|
540 |
|
541 | createTask: (params) ->
|
542 | params.adapter = @robot.adapterName or 'test'
|
543 | @getBotPHID()
|
544 | .then (bot_phid) =>
|
545 | params.bot_phid = bot_phid
|
546 | if params.user?
|
547 | if not params.user?.name?
|
548 | params.user = { name: params.user }
|
549 | else
|
550 | params.user = { name: @robot.name, phid: params.bot_phid }
|
551 | @getTemplate(params.template)
|
552 | .then (description) =>
|
553 | if description?
|
554 | if params.description?
|
555 | params.description += "\n\n#{description}"
|
556 | else
|
557 | params.description = description
|
558 | @getProject(params.project)
|
559 | .then (projectparams) =>
|
560 | params.projectphid = projectparams.data.phid
|
561 | @getUser(params.user, params.user)
|
562 | .then (userPHID) =>
|
563 | query = {
|
564 | 'transactions[0][type]': 'title',
|
565 | 'transactions[0][value]': "#{params.title}",
|
566 | 'transactions[1][type]': 'comment',
|
567 | 'transactions[1][value]': "(created by #{params.user.name} on #{params.adapter})",
|
568 | 'transactions[2][type]': 'subscribers.add',
|
569 | 'transactions[2][value][0]': "#{userPHID}",
|
570 | 'transactions[3][type]': 'subscribers.remove',
|
571 | 'transactions[3][value][0]': "#{params.bot_phid}",
|
572 | 'transactions[4][type]': 'projects.add',
|
573 | 'transactions[4][value][]': "#{params.projectphid}"
|
574 | }
|
575 | next = 5
|
576 | if params.description?
|
577 | query["transactions[#{next}][type]"] = 'description'
|
578 | query["transactions[#{next}][value]"] = "#{params.description}"
|
579 | next += 1
|
580 | if params.assign? and @data.users?[params.assign]?.phid
|
581 | owner = @data.users[params.assign]?.phid
|
582 | query["transactions[#{next}][type]"] = 'owner'
|
583 | query["transactions[#{next}][value]"] = owner
|
584 | @request(query, 'maniphest.edit')
|
585 | .then (body) ->
|
586 | id = body.result.object.id
|
587 | url = process.env.PHABRICATOR_URL + "/T#{id}"
|
588 | { id: id, url: url, user: params.user }
|
589 |
|
590 | createPaste: (user, title) ->
|
591 | adapter = @robot.adapterName
|
592 | bot_phid = null
|
593 | @getBotPHID()
|
594 | .bind(bot_phid)
|
595 | .then (bot_phid) =>
|
596 | @getUser(user, user)
|
597 | .then (userPhid) =>
|
598 | query = {
|
599 | 'transactions[0][type]': 'title',
|
600 | 'transactions[0][value]': "#{title}",
|
601 | 'transactions[1][type]': 'text',
|
602 | 'transactions[1][value]': "(created by #{user.name} on #{adapter})",
|
603 | 'transactions[2][type]': 'subscribers.add',
|
604 | 'transactions[2][value][0]': "#{userPhid}",
|
605 | 'transactions[3][type]': 'subscribers.remove',
|
606 | 'transactions[3][value][0]': "#{@bot_phid}"
|
607 | }
|
608 | @request(query, 'paste.edit')
|
609 | .then (body) ->
|
610 | body.result.object.id
|
611 |
|
612 | addComment: (user, id, comment) ->
|
613 | @getBotPHID()
|
614 | .then (bot_phid) =>
|
615 | query = {
|
616 | 'objectIdentifier': id,
|
617 | 'transactions[0][type]': 'comment',
|
618 | 'transactions[0][value]': "#{comment} (#{user.name})",
|
619 | 'transactions[1][type]': 'subscribers.remove',
|
620 | 'transactions[1][value][0]': "#{bot_phid}"
|
621 | }
|
622 | @request(query, 'maniphest.edit')
|
623 | .then (body) ->
|
624 | id
|
625 |
|
626 | doActions: (user, id, commandString, comment) ->
|
627 | @getBotPHID()
|
628 | .bind({ bot_phid: null })
|
629 | .then (bot_phid) =>
|
630 | @bot_phid = bot_phid
|
631 | @taskInfo id
|
632 | .then (body) =>
|
633 | @parseAction user, body.result, commandString
|
634 | .then (results) =>
|
635 | if results.data.length > 0
|
636 | query = {
|
637 | 'objectIdentifier': "T#{id}",
|
638 | 'transactions[0][type]': 'subscribers.remove',
|
639 | 'transactions[0][value][0]': "#{@bot_phid}"
|
640 | }
|
641 | project_add = []
|
642 | project_remove = []
|
643 | subscriber_add = []
|
644 | subscriber_remove = []
|
645 | i = 0
|
646 | for action in results.data
|
647 | if action.type is 'projects.add'
|
648 | project_add.push action.value
|
649 | else if action.type is 'projects.remove'
|
650 | project_remove.push action.value
|
651 | else if action.type is 'subscribers.add'
|
652 | subscriber_add.push action.value
|
653 | else if action.type is 'subscribers.remove'
|
654 | subscriber_remove.push action.value
|
655 | else
|
656 | i = i + 1
|
657 | query['transactions[' + i + '][type]'] = action.type
|
658 | query['transactions[' + i + '][value]'] = action.value
|
659 |
|
660 | if project_add.length > 0
|
661 | i = i + 1
|
662 | query['transactions[' + i + '][type]'] = 'projects.add'
|
663 | for phid, j in project_add
|
664 | query['transactions[' + i + '][value][' + j + ']'] = phid
|
665 |
|
666 | if project_remove.length > 0
|
667 | i = i + 1
|
668 | query['transactions[' + i + '][type]'] = 'projects.remove'
|
669 | for phid, j in project_remove
|
670 | query['transactions[' + i + '][value][' + j + ']'] = phid
|
671 |
|
672 | if subscriber_add.length > 0
|
673 | i = i + 1
|
674 | query['transactions[' + i + '][type]'] = 'subscribers.add'
|
675 | for phid, j in subscriber_add
|
676 | query['transactions[' + i + '][value][' + j + ']'] = phid
|
677 |
|
678 | if subscriber_remove.length > 0
|
679 | i = i + 1
|
680 | query['transactions[' + i + '][type]'] = 'subscribers.remove'
|
681 | for phid, j in subscriber_remove
|
682 | query['transactions[' + i + '][value][' + j + ']'] = phid
|
683 |
|
684 | i = i + 1
|
685 | query['transactions[' + i + '][type]'] = 'comment'
|
686 | if comment?
|
687 | query['transactions[' + i + '][value]'] = "#{comment} (#{user.name})"
|
688 | else
|
689 | query['transactions[' + i + '][value]'] =
|
690 | "#{results.messages.join(', ')} (by #{user.name})"
|
691 | @request(query, 'maniphest.edit')
|
692 | .then (body) ->
|
693 | { id: id, message: results.messages.join(', '), notices: results.notices }
|
694 | else
|
695 | { id: id, message: results.messages.join(', '), notices: results.notices }
|
696 | .catch (e) ->
|
697 | { id: id, message: null, notices: [ e ] }
|
698 |
|
699 | parseAction: (user, item, str, payload = { data: [], messages: [], notices: [] }) ->
|
700 | return new Promise (res, err) =>
|
701 | p = new RegExp('^(in|not in|on|for|is|to|sub|unsub) ([^ ]*)')
|
702 | r = str.trim().match p
|
703 | switch r[1]
|
704 | when 'in'
|
705 | @getProject(r[2])
|
706 | .then (projectData) =>
|
707 | phid = projectData.data.phid
|
708 | if phid not in item.projectPHIDs
|
709 | payload.data.push({ type: 'projects.add', value: [phid] })
|
710 | payload.messages.push("been added to #{r[2]}")
|
711 | else
|
712 | payload.notices.push("T#{item.id} is already in #{r[2]}")
|
713 | next = str.trim().replace(p, '')
|
714 | if next.trim() isnt ''
|
715 | res @parseAction(user, item, next, payload)
|
716 | else
|
717 | res payload
|
718 | .catch (e) ->
|
719 | payload.notices.push(e)
|
720 | res payload
|
721 | when 'not in'
|
722 | @getProject(r[2])
|
723 | .then (projectData) =>
|
724 | phid = projectData.data.phid
|
725 | if phid in item.projectPHIDs
|
726 | payload.data.push({ type: 'projects.remove', value: [phid] })
|
727 | payload.messages.push("been removed from #{r[2]}")
|
728 | else
|
729 | payload.notices.push("T#{item.id} is already not in #{r[2]}")
|
730 | next = str.trim().replace(p, '')
|
731 | if next.trim() isnt ''
|
732 | res @parseAction(user, item, next, payload)
|
733 | else
|
734 | res payload
|
735 | .catch (e) ->
|
736 | payload.notices.push(e)
|
737 | res payload
|
738 | when 'on', 'for'
|
739 | @getUser(user, { name: r[2] })
|
740 | .then (userphid) =>
|
741 | if r[2] is 'me'
|
742 | r[2] = user.name
|
743 | payload.data.push({ type: 'owner', value: userphid })
|
744 | payload.messages.push("owner set to #{r[2]}")
|
745 | next = str.trim().replace(p, '')
|
746 | if next.trim() isnt ''
|
747 | res @parseAction(user, item, next, payload)
|
748 | else
|
749 | res payload
|
750 | .catch (e) ->
|
751 | payload.notices.push(e)
|
752 | res payload
|
753 | when 'sub'
|
754 | @getUser(user, { name: r[2] })
|
755 | .then (userphid) =>
|
756 | if r[2] is 'me'
|
757 | r[2] = user.name
|
758 | if userphid not in item.ccPHIDs
|
759 | payload.data.push({ type: 'subscribers.add', value: [userphid] })
|
760 | payload.messages.push("subscribed #{r[2]}")
|
761 | else
|
762 | payload.notices.push("#{r[2]} already subscribed to T#{item.id}")
|
763 | next = str.trim().replace(p, '')
|
764 | if next.trim() isnt ''
|
765 | res @parseAction(user, item, next, payload)
|
766 | else
|
767 | res payload
|
768 | .catch (e) ->
|
769 | payload.notices.push(e)
|
770 | res payload
|
771 | when 'unsub'
|
772 | @getUser(user, { name: r[2] })
|
773 | .then (userphid) =>
|
774 | if r[2] is 'me'
|
775 | r[2] = user.name
|
776 | if userphid in item.ccPHIDs
|
777 | payload.data.push({ type: 'subscribers.remove', value: [userphid] })
|
778 | payload.messages.push("unsubscribed #{r[2]}")
|
779 | else
|
780 | payload.notices.push("#{r[2]} is not subscribed to T#{item.id}")
|
781 | next = str.trim().replace(p, '')
|
782 | if next.trim() isnt ''
|
783 | res @parseAction(user, item, next, payload)
|
784 | else
|
785 | res payload
|
786 | .catch (e) ->
|
787 | payload.notices.push(e)
|
788 | res payload
|
789 | when 'to'
|
790 | if not item.projectPHIDs? or item.projectPHIDs.length is 0
|
791 | err 'This item has no tag/project yet.'
|
792 | else
|
793 | cols = Promise.map item.projectPHIDs, (phid) =>
|
794 | @getProject(phid)
|
795 | .then (projectData) ->
|
796 | for i in Object.keys(projectData.data.columns)
|
797 | if (new RegExp(r[2])).test i
|
798 | return { colname: i, colphid: projectData.data.columns[i] }
|
799 | Promise.all(cols)
|
800 | .then (cols) =>
|
801 | cols = cols.filter (c) ->
|
802 | c?
|
803 | if cols.length > 0
|
804 | payload.data.push({ type: 'column', value: cols[0].colphid })
|
805 | payload.messages.push("column changed to #{cols[0].colname}")
|
806 | else
|
807 | payload.notices.push("T#{item.id} cannot be moved to #{r[2]}")
|
808 | next = str.trim().replace(p, '')
|
809 | if next.trim() isnt ''
|
810 | res @parseAction(user, item, next, payload)
|
811 | else
|
812 | res payload
|
813 | .catch (e) ->
|
814 | payload.notices.push(e)
|
815 | res payload
|
816 | when 'is'
|
817 | if @statuses[r[2]]?
|
818 | payload.data.push({ type: 'status', value: @statuses[r[2]] })
|
819 | payload.messages.push("status set to #{r[2]}")
|
820 | else if @priorities[r[2]]?
|
821 | payload.data.push({ type: 'priority', value: @priorities[r[2]] })
|
822 | payload.messages.push("priority set to #{r[2]}")
|
823 | else
|
824 | err "Unknown status or priority '#{r[2]}', please choose in " +
|
825 | Object.keys(@statuses).join(', ') + ', ' +
|
826 | Object.keys(@priorities).join(', ')
|
827 | next = str.trim().replace(p, '')
|
828 | if next.trim() isnt ''
|
829 | res @parseAction(user, item, next, payload)
|
830 | else
|
831 | res payload
|
832 |
|
833 | listTasks: (projphid) ->
|
834 | query = {
|
835 | 'projectPHIDs[0]': "#{projphid}",
|
836 | 'status': 'status-open'
|
837 | }
|
838 | @request query, 'maniphest.query'
|
839 |
|
840 | nextCheckbox: (user, id, key) ->
|
841 | return new Promise (res, err) =>
|
842 | query = { task_id: id }
|
843 | @request(query, 'maniphest.info')
|
844 | .then (body) =>
|
845 | @recordId user, id
|
846 | lines = body.result.description.split('\n')
|
847 | reg = new RegExp("^\\[ \\] .*#{key or ''}", 'i')
|
848 | found = null
|
849 | for line in lines
|
850 | if reg.test line
|
851 | found = line
|
852 | break
|
853 | if found?
|
854 | res found
|
855 | else
|
856 | if key?
|
857 | err "The task T#{id} has no unchecked checkbox matching #{key}."
|
858 | else
|
859 | err "The task T#{id} has no unchecked checkboxes."
|
860 | .catch (e) ->
|
861 | err e
|
862 |
|
863 | prevCheckbox: (user, id, key) ->
|
864 | return new Promise (res, err) =>
|
865 | query = { task_id: id }
|
866 | @request(query, 'maniphest.info')
|
867 | .then (body) =>
|
868 | @recordId user, id
|
869 | lines = body.result.description.split('\n').reverse()
|
870 | reg = new RegExp("^\\[x\\] .*#{key or ''}", 'i')
|
871 | found = null
|
872 | for line in lines
|
873 | if reg.test line
|
874 | found = line
|
875 | break
|
876 | if found?
|
877 | res found
|
878 | else
|
879 | if key?
|
880 | err "The task T#{id} has no checked checkbox matching #{key}."
|
881 | else
|
882 | err "The task T#{id} has no checked checkboxes."
|
883 | .catch (e) ->
|
884 | err e
|
885 |
|
886 | updateTask: (id, description, comment) =>
|
887 | @getBotPHID()
|
888 | .then (bot_phid) =>
|
889 | editquery = {
|
890 | 'objectIdentifier': "T#{id}",
|
891 | 'transactions[0][type]': 'description'
|
892 | 'transactions[0][value]': "#{description}"
|
893 | 'transactions[1][type]': 'subscribers.remove',
|
894 | 'transactions[1][value][0]': "#{bot_phid}",
|
895 | 'transactions[2][type]': 'comment',
|
896 | 'transactions[2][value]': "#{comment}"
|
897 | }
|
898 | @request(editquery, 'maniphest.edit')
|
899 |
|
900 | checkCheckbox: (user, id, key, withNext, usercomment) ->
|
901 | return new Promise (res, err) =>
|
902 | query = { task_id: id }
|
903 | @request(query, 'maniphest.info')
|
904 | .then (body) =>
|
905 | @recordId user, id
|
906 | lines = body.result.description.split('\n')
|
907 | reg = new RegExp("^\\[ \\] .*#{key or ''}", 'i')
|
908 | found = null
|
909 | foundNext = null
|
910 | updated = [ ]
|
911 | extra = if key? then " matching #{key}" else ''
|
912 | for line in lines
|
913 | if not found? and reg.test line
|
914 | line = line.replace('[ ] ', '[x] ')
|
915 | found = line
|
916 | else if withNext? and found? and not foundNext? and reg.test line
|
917 | foundNext = line
|
918 | updated.push line
|
919 | if found?
|
920 | comment = "#{user.name} checked:\n#{found}"
|
921 | comment += "\n#{usercomment}" if usercomment?
|
922 | description = updated.join('\n')
|
923 | @updateTask(id, description, comment)
|
924 | .then (body) ->
|
925 | if withNext? and not foundNext?
|
926 | foundNext = "there is no more unchecked checkbox#{extra}."
|
927 | res [ found, foundNext ]
|
928 | .catch (e) ->
|
929 | err e
|
930 | else
|
931 | err "The task T#{id} has no unchecked checkbox#{extra}."
|
932 | .catch (e) ->
|
933 | err e
|
934 |
|
935 | uncheckCheckbox: (user, id, key, withNext, usercomment) ->
|
936 | return new Promise (res, err) =>
|
937 | query = { task_id: id }
|
938 | @request(query, 'maniphest.info')
|
939 | .then (body) =>
|
940 | @recordId user, id
|
941 | lines = body.result.description.split('\n').reverse()
|
942 | reg = new RegExp("^\\[x\\] .*#{key or ''}", 'i')
|
943 | found = null
|
944 | foundNext = null
|
945 | updated = [ ]
|
946 | extra = if key? then " matching #{key}" else ''
|
947 | for line in lines
|
948 | if not found? and reg.test line
|
949 | line = line.replace('[x] ', '[ ] ')
|
950 | found = line
|
951 | else if withNext? and found? and not foundNext? and reg.test line
|
952 | foundNext = line
|
953 | updated.push line
|
954 | if found?
|
955 | comment = "#{user.name} unchecked:\n#{found}"
|
956 | comment += "\n#{usercomment}" if usercomment?
|
957 | description = updated.reverse().join('\n')
|
958 | @updateTask(id, description, comment)
|
959 | .then (body) ->
|
960 | if withNext? and not foundNext?
|
961 | foundNext = "there is no more checked checkbox#{extra}."
|
962 | res [ found, foundNext ]
|
963 | .catch (e) ->
|
964 | err e
|
965 | else
|
966 | err "The task T#{id} has no checked checkbox#{extra}."
|
967 | .catch (e) ->
|
968 | err e
|
969 |
|
970 |
|
971 |
|
972 | getTemplate: (name) =>
|
973 | return new Promise (res, err) =>
|
974 | if name?
|
975 | if @data.templates[name]?
|
976 | query = {
|
977 | task_id: @data.templates[name].task
|
978 | }
|
979 | @request(query, 'maniphest.info')
|
980 | .then (body) ->
|
981 | res body.result.description
|
982 | .catch (e) ->
|
983 | err e
|
984 | else
|
985 | err "There is no template named '#{name}'."
|
986 | else
|
987 | res null
|
988 |
|
989 | addTemplate: (name, taskid) ->
|
990 | return new Promise (res, err) =>
|
991 | if @data.templates[name]?
|
992 | err "Template '#{name}' already exists."
|
993 | else
|
994 | data = @data
|
995 | @taskInfo(taskid)
|
996 | .then (body) ->
|
997 | data.templates[name] = { task: taskid }
|
998 | res 'Ok'
|
999 | .catch (e) ->
|
1000 | err e
|
1001 |
|
1002 | showTemplate: (name) ->
|
1003 | return new Promise (res, err) =>
|
1004 | if @data.templates[name]?
|
1005 | res @data.templates[name]
|
1006 | else
|
1007 | err "Template '#{name}' was not found."
|
1008 |
|
1009 | searchTemplate: (term) ->
|
1010 | return new Promise (res, err) =>
|
1011 | back = [ ]
|
1012 | for name, template of @data.templates
|
1013 | if new RegExp(term).test name
|
1014 | back.push { name: name, task: template.task }
|
1015 | if back.length is 0
|
1016 | if term?
|
1017 | err "No template matches '#{term}'."
|
1018 | else
|
1019 | err 'There is no template defined.'
|
1020 | else
|
1021 | res back
|
1022 |
|
1023 | removeTemplate: (name) ->
|
1024 | return new Promise (res, err) =>
|
1025 | if @data.templates[name]?
|
1026 | delete @data.templates[name]
|
1027 | res 'Ok'
|
1028 | else
|
1029 | err "Template '#{name}' was not found."
|
1030 |
|
1031 | updateTemplate: (name, taskid) ->
|
1032 | return new Promise (res, err) =>
|
1033 | if @data.templates[name]?
|
1034 | data = @data
|
1035 | @taskInfo(taskid)
|
1036 | .then (body) ->
|
1037 | data.templates[name] = { task: taskid }
|
1038 | res 'Ok'
|
1039 | .catch (e) ->
|
1040 | err e
|
1041 | else
|
1042 | err "Template '#{name}' was not found."
|
1043 |
|
1044 | renameTemplate: (name, newname) ->
|
1045 | return new Promise (res, err) =>
|
1046 | if @data.templates[name]?
|
1047 | if @data.templates[newname]?
|
1048 | err "Template '#{newname}' already exists."
|
1049 | else
|
1050 | @data.templates[newname] = { task: @data.templates[name].task }
|
1051 | delete @data.templates[name]
|
1052 | res 'Ok'
|
1053 | else
|
1054 | err "Template '#{name}' was not found."
|
1055 |
|
1056 |
|
1057 |
|
1058 | module.exports = Phabricator
|