-
Notifications
You must be signed in to change notification settings - Fork 583
/
mailcatcher.js.coffee
323 lines (264 loc) · 10.7 KB
/
mailcatcher.js.coffee
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
#= require modernizr
#= require jquery
#= require date
#= require favcount
#= require flexie
#= require keymaster
# Add a new jQuery selector expression which does a case-insensitive :contains
jQuery.expr[":"].icontains = (a, i, m) ->
(a.textContent ? a.innerText ? "").toUpperCase().indexOf(m[3].toUpperCase()) >= 0
class MailCatcher
constructor: ->
$("#messages tr").live "click", (e) =>
e.preventDefault()
@loadMessage $(e.currentTarget).attr("data-message-id")
$("input[name=search]").keyup (e) =>
query = $.trim $(e.currentTarget).val()
if query
@searchMessages query
else
@clearSearch()
$("#message .views .format.tab a").live "click", (e) =>
e.preventDefault()
@loadMessageBody @selectedMessage(), $($(e.currentTarget).parent("li")).data("message-format")
$("#message iframe").load =>
@decorateMessageBody()
$("#resizer").live
mousedown: (e) =>
e.preventDefault()
$(window).bind events =
mouseup: (e) =>
e.preventDefault()
$(window).unbind events
mousemove: (e) =>
e.preventDefault()
@resizeTo e.clientY
@resizeToSaved()
$("nav.app .clear a").live "click", (e) =>
e.preventDefault()
if confirm "You will lose all your received messages.\n\nAre you sure you want to clear all messages?"
$.ajax
url: new URL("messages")
type: "DELETE"
success: =>
@unselectMessage()
@updateMessagesCount()
error: ->
alert "Error while clearing all messages."
$("nav.app .quit a").live "click", (e) =>
e.preventDefault()
if confirm "You will lose all your received messages.\n\nAre you sure you want to quit?"
$.ajax
type: "DELETE"
success: ->
location.replace $("body > header h1 a").attr("href")
error: ->
alert "Error while quitting."
@favcount = new Favcount($("""link[rel="icon"]""").attr("href"))
key "up", =>
if @selectedMessage()
@loadMessage $("#messages tr.selected").prev().data("message-id")
else
@loadMessage $("#messages tbody tr[data-message-id]:first").data("message-id")
false
key "down", =>
if @selectedMessage()
@loadMessage $("#messages tr.selected").next().data("message-id")
else
@loadMessage $("#messages tbody tr[data-message-id]:first").data("message-id")
false
key "⌘+up, ctrl+up", =>
@loadMessage $("#messages tbody tr[data-message-id]:first").data("message-id")
false
key "⌘+down, ctrl+down", =>
@loadMessage $("#messages tbody tr[data-message-id]:last").data("message-id")
false
key "left", =>
@openTab @previousTab()
false
key "right", =>
@openTab @nextTab()
false
key "backspace, delete", =>
id = @selectedMessage()
if id?
$.ajax
url: new URL("messages/#{id}")
type: "DELETE"
success: =>
messageRow = $("""#messages tbody tr[data-message-id="#{id}"]""")
switchTo = messageRow.next().data("message-id") || messageRow.prev().data("message-id")
messageRow.remove()
if switchTo
@loadMessage switchTo
else
@unselectMessage()
@updateMessagesCount()
error: ->
alert "Error while removing message."
false
@refresh()
@subscribe()
# Only here because Safari's Date parsing *sucks*
# We throw away the timezone, but you could use it for something...
parseDateRegexp: /^(\d{4})[-\/\\](\d{2})[-\/\\](\d{2})(?:\s+|T)(\d{2})[:-](\d{2})[:-](\d{2})(?:([ +-]\d{2}:\d{2}|\s*\S+|Z?))?$/
parseDate: (date) ->
if match = @parseDateRegexp.exec(date)
new Date match[1], match[2] - 1, match[3], match[4], match[5], match[6], 0
offsetTimeZone: (date) ->
offset = Date.now().getTimezoneOffset() * 60000 #convert timezone difference to milliseconds
date.setTime(date.getTime() - offset)
date
formatDate: (date) ->
date &&= @parseDate(date) if typeof(date) == "string"
date &&= @offsetTimeZone(date)
date &&= date.toString("dddd, d MMM yyyy h:mm:ss tt")
messagesCount: ->
$("#messages tr").length - 1
updateMessagesCount: ->
@favcount.set(@messagesCount())
document.title = 'MailCatcher (' + @messagesCount() + ')'
tabs: ->
$("#message ul").children(".tab")
getTab: (i) =>
$(@tabs()[i])
selectedTab: =>
@tabs().index($("#message li.tab.selected"))
openTab: (i) =>
@getTab(i).children("a").click()
previousTab: (tab)=>
i = if tab || tab is 0 then tab else @selectedTab() - 1
i = @tabs().length - 1 if i < 0
if @getTab(i).is(":visible")
i
else
@previousTab(i - 1)
nextTab: (tab) =>
i = if tab then tab else @selectedTab() + 1
i = 0 if i > @tabs().length - 1
if @getTab(i).is(":visible")
i
else
@nextTab(i + 1)
haveMessage: (message) ->
message = message.id if message.id?
$("""#messages tbody tr[data-message-id="#{message}"]""").length > 0
selectedMessage: ->
$("#messages tr.selected").data "message-id"
searchMessages: (query) ->
selector = (":icontains('#{token}')" for token in query.split /\s+/).join("")
$rows = $("#messages tbody tr")
$rows.not(selector).hide()
$rows.filter(selector).show()
clearSearch: ->
$("#messages tbody tr").show()
addMessage: (message) ->
$("<tr />").attr("data-message-id", message.id.toString())
.append($("<td/>").text(message.sender or "No sender").toggleClass("blank", !message.sender))
.append($("<td/>").text((message.recipients || []).join(", ") or "No receipients").toggleClass("blank", !message.recipients.length))
.append($("<td/>").text(message.subject or "No subject").toggleClass("blank", !message.subject))
.append($("<td/>").text(@formatDate(message.created_at)))
.prependTo($("#messages tbody"))
@updateMessagesCount()
scrollToRow: (row) ->
relativePosition = row.offset().top - $("#messages").offset().top
if relativePosition < 0
$("#messages").scrollTop($("#messages").scrollTop() + relativePosition - 20)
else
overflow = relativePosition + row.height() - $("#messages").height()
if overflow > 0
$("#messages").scrollTop($("#messages").scrollTop() + overflow + 20)
unselectMessage: ->
$("#messages tbody, #message .metadata dd").empty()
$("#message .metadata .attachments").hide()
$("#message iframe").attr("src", "about:blank")
null
loadMessage: (id) ->
id = id.id if id?.id?
id ||= $("#messages tr.selected").attr "data-message-id"
if id?
$("#messages tbody tr:not([data-message-id='#{id}'])").removeClass("selected")
messageRow = $("#messages tbody tr[data-message-id='#{id}']")
messageRow.addClass("selected")
@scrollToRow(messageRow)
$.getJSON "messages/#{id}.json", (message) =>
$("#message .metadata dd.created_at").text(@formatDate message.created_at)
$("#message .metadata dd.from").text(message.sender)
$("#message .metadata dd.to").text((message.recipients || []).join(", "))
$("#message .metadata dd.subject").text(message.subject)
$("#message .views .tab.format").each (i, el) ->
$el = $(el)
format = $el.attr("data-message-format")
if $.inArray(format, message.formats) >= 0
$el.find("a").attr("href", "messages/#{id}.#{format}")
$el.show()
else
$el.hide()
if $("#message .views .tab.selected:not(:visible)").length
$("#message .views .tab.selected").removeClass("selected")
$("#message .views .tab:visible:first").addClass("selected")
if message.attachments.length
$ul = $("<ul/>").appendTo($("#message .metadata dd.attachments").empty())
$.each message.attachments, (i, attachment) ->
$ul.append($("<li>").append($("<a>").attr("href", attachment["href"]).addClass(attachment["type"].split("/", 1)[0]).addClass(attachment["type"].replace("/", "-")).text(attachment["filename"])))
$("#message .metadata .attachments").show()
else
$("#message .metadata .attachments").hide()
$("#message .views .download a").attr("href", "messages/#{id}.eml")
@loadMessageBody()
# XXX: These should probably cache their iframes for the current message now we're using a remote service:
loadMessageBody: (id, format) ->
id ||= @selectedMessage()
format ||= $("#message .views .tab.format.selected").attr("data-message-format")
format ||= "html"
$("""#message .views .tab[data-message-format="#{format}"]:not(.selected)""").addClass("selected")
$("""#message .views .tab:not([data-message-format="#{format}"]).selected""").removeClass("selected")
if id?
$("#message iframe").attr("src", "messages/#{id}.#{format}")
decorateMessageBody: ->
format = $("#message .views .tab.format.selected").attr("data-message-format")
switch format
when "html"
body = $("#message iframe").contents().find("body")
$("a", body).attr("target", "_blank")
when "plain"
message_iframe = $("#message iframe").contents()
text = message_iframe.text()
text = text.replace(/((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?)/g, """<a href="$1" target="_blank">$1</a>""")
text = text.replace(/\n/g, "<br/>")
message_iframe.find("html").html("<html><body>#{text}</html></body>")
refresh: ->
$.getJSON "messages", (messages) =>
$.each messages, (i, message) =>
unless @haveMessage message
@addMessage message
@updateMessagesCount()
subscribe: ->
if WebSocket?
@subscribeWebSocket()
else
@subscribePoll()
subscribeWebSocket: ->
secure = window.location.protocol is "https:"
url = new URL("messages", document.baseURI)
console.log(url)
url.protocol = if secure then "wss" else "ws"
console.log(url)
console.log(url.toString())
@websocket = new WebSocket(url.toString())
console.log(@websocket)
@websocket.onmessage = (event) =>
@addMessage $.parseJSON event.data
subscribePoll: ->
unless @refreshInterval?
@refreshInterval = setInterval (=> @refresh()), 1000
resizeToSavedKey: "mailcatcherSeparatorHeight"
resizeTo: (height) ->
$("#messages").css
height: height - $("#messages").offset().top
window.localStorage?.setItem(@resizeToSavedKey, height)
resizeToSaved: ->
height = parseInt(window.localStorage?.getItem(@resizeToSavedKey))
unless isNaN height
@resizeTo height
$ -> window.MailCatcher = new MailCatcher