UNPKG

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