-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnw-angular-updater.coffee
89 lines (86 loc) · 2.5 KB
/
nw-angular-updater.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
GUI = require 'nw.gui'
fs = require 'fs'
http = require 'http'
path = require 'path'
child_process = require 'child_process'
class UpdateService
__DIR = path.dirname process.execPath
constructor: (@q, @http, {@infoUrl,@downloadUrl,@filename,@currentVersion}, @auto=true) ->
if not @infoUrl or not @downloadUrl or not @filename or not @currentVersion
throw new Error 'Not Configured'
if @auto
@checkAndUpdate()
else
@check
check: ->
deferred = @q.defer()
@updateRequired = false
@checking = true
@http.get @infoUrl
.success (data) =>
@checking = false
@updateRequired = data.version > @currentVersion
deferred.resolve @updateRequired
deferred.promise
download: ->
deferred = @q.defer()
@downloading = true
file = fs.createWriteStream path.join __DIR, "#{@filename}.download"
http.get @downloadUrl, (response) =>
response.pipe file
response.on 'end', =>
@downloading = false
@restartRequired = true
deferred.resolve true
.on 'error', (err) ->
@downloading = false
@restartRequired = false
deferred.reject err
deferred.promise
unlink: ->
deferred = @q.defer()
fs.unlink path.join(__DIR, @filename), (err) ->
if err
deferred.reject err
else
deferred.resolve true
deferred.promise
rename: ->
deferred = @q.defer()
fs.rename (path.join __DIR, "#{@filename}.download"), (path.join __DIR, @filename), (err) ->
if err
deferred.reject err
else
deferred.resolve true
deferred.promise
checkAndUpdate: ->
@check()
.then =>
return @q.reject() if not @updateRequired
.then =>
@download()
.then =>
@unlink()
.then =>
@rename()
.catch (err) =>
console.log 'error', err
@checking = @downloading = @restartRequired = false
restart: ->
child = child_process.spawn process.execPath, [], detached: true
#Don't wait for it
child.unref();
#Quit current
GUI.window.hide(); # hide window to prevent black display
GUI.app.quit(); # quit node-webkit app
class UpdateServiceProvider
setInfoUrl: (@infoUrl) -> @
setDownloadUrl: (@downloadUrl) -> @
setFilename: (@filename) -> @
setCurrentVersion: (@currentVersion) -> @
setAuto: (@auto) -> @
$get: ['$q', '$http', (q, http) ->
new UpdateService q, http, {@infoUrl,@downloadUrl,@filename,@currentVersion}, @auto
]
angular.module 'nwUpdater', []
.provider 'nwUpdate', UpdateServiceProvider