2016-01-09 06:31:33 +08:00
|
|
|
_ = require 'underscore'
|
|
|
|
Rx = require 'rx-lite'
|
|
|
|
|
2016-01-16 06:26:07 +08:00
|
|
|
NylasAPI = require './flux/nylas-api'
|
|
|
|
DatabaseStore = require './flux/stores/database-store'
|
|
|
|
Thread = require './flux/models/thread'
|
|
|
|
MutableQuerySubscription = require './flux/models/mutable-query-subscription'
|
2016-01-09 06:31:33 +08:00
|
|
|
|
2016-01-16 06:26:07 +08:00
|
|
|
class SearchSubscription extends MutableQuerySubscription
|
2016-01-09 06:31:33 +08:00
|
|
|
|
2016-01-19 14:37:49 +08:00
|
|
|
constructor: (@_terms, @_accountIds) ->
|
2016-01-16 06:26:07 +08:00
|
|
|
super(null, {asResultSet: true})
|
|
|
|
|
2016-01-22 07:58:58 +08:00
|
|
|
@_termsVersion = 0
|
2016-01-09 06:31:33 +08:00
|
|
|
_.defer => @retrievePage(0)
|
|
|
|
|
|
|
|
terms: =>
|
|
|
|
@_terms
|
|
|
|
|
|
|
|
setTerms: (terms) =>
|
|
|
|
@_terms = terms
|
2016-01-22 07:58:58 +08:00
|
|
|
@_termsVersion += 1
|
2016-01-09 06:31:33 +08:00
|
|
|
@retrievePage(0)
|
|
|
|
|
2016-01-16 06:26:07 +08:00
|
|
|
replaceRange: (range) =>
|
2016-01-19 16:00:00 +08:00
|
|
|
# TODO
|
2016-01-09 06:31:33 +08:00
|
|
|
|
|
|
|
# Accessing Data
|
|
|
|
|
|
|
|
retrievePage: (idx) =>
|
2016-01-22 07:58:58 +08:00
|
|
|
termsVersion = @_termsVersion += 1
|
|
|
|
resultCount = 0
|
2016-01-19 16:00:00 +08:00
|
|
|
resultIds = []
|
2016-01-09 06:31:33 +08:00
|
|
|
|
2016-02-06 06:28:07 +08:00
|
|
|
resultReturned = =>
|
|
|
|
# Don't emit a "result" until we have at least one thread to display.
|
|
|
|
# Otherwise it will show "No Results Found"
|
|
|
|
if resultIds.length > 0 or resultCount is @_accountIds.length
|
|
|
|
query = DatabaseStore.findAll(Thread).where(id: resultIds).order(Thread.attributes.lastMessageReceivedTimestamp.descending())
|
|
|
|
@replaceQuery(query)
|
|
|
|
|
2016-01-19 16:00:00 +08:00
|
|
|
@_accountIds.forEach (aid) =>
|
2016-01-19 14:37:49 +08:00
|
|
|
NylasAPI.makeRequest
|
|
|
|
method: 'GET'
|
|
|
|
path: "/threads/search?q=#{encodeURIComponent(@_terms)}"
|
|
|
|
accountId: aid
|
|
|
|
json: true
|
2016-03-25 06:16:43 +08:00
|
|
|
timeout: 45000
|
2016-01-19 14:37:49 +08:00
|
|
|
returnsModel: true
|
2016-02-06 06:28:07 +08:00
|
|
|
|
2016-01-19 16:00:00 +08:00
|
|
|
.then (threads) =>
|
2016-01-22 07:58:58 +08:00
|
|
|
return unless @_termsVersion is termsVersion
|
|
|
|
resultCount += 1
|
2016-01-19 16:00:00 +08:00
|
|
|
resultIds = resultIds.concat _.pluck(threads, 'id')
|
2016-02-06 06:28:07 +08:00
|
|
|
resultReturned()
|
2016-01-22 07:58:58 +08:00
|
|
|
|
2016-02-06 06:28:07 +08:00
|
|
|
.catch (err) =>
|
|
|
|
resultCount += 1
|
|
|
|
resultReturned()
|
2016-01-09 06:31:33 +08:00
|
|
|
|
2016-01-16 06:26:07 +08:00
|
|
|
module.exports = SearchSubscription
|