forked from dalefarnsworth-dmr/editcp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathradio.go
873 lines (721 loc) · 20.9 KB
/
radio.go
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
// Copyright 2017-2021 Dale Farnsworth. All rights reserved.
// Dale Farnsworth
// 1007 W Mendoza Ave
// Mesa, AZ 85210
// USA
//
// This file is part of Editcp.
//
// Editcp is free software: you can redistribute it and/or modify
// it under the terms of version 3 of the GNU General Public License
// as published by the Free Software Foundation.
//
// Editcp is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Editcp. If not, see <http://www.gnu.org/licenses/>.
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"time"
"github.com/dalefarnsworth-dmr/codeplug"
l "github.com/dalefarnsworth-dmr/debug"
"github.com/dalefarnsworth-dmr/dfu"
"github.com/dalefarnsworth-dmr/ui"
"github.com/dalefarnsworth-dmr/userdb"
"github.com/therecipe/qt/core"
)
type modelURL struct {
model string
url string
}
func writeMD380toolsUsers() {
title := "Write user database to radio"
text := `
The users database contains DMR ID numbers and callsigns of all registered
users. It can only be be written to radios that have been upgraded to the
md380tools firmware. See https://github.com/travisgoodspeed/md380tools.
WARNING: Corruption may occur if a signal is received while writing to the
radio. The radio should be tuned to an unprogrammed (or at least quiet)
channel while writing the new user database.`
cancel, download := userdbDialog(title, text)
if cancel {
return
}
locType := core.QStandardPaths__CacheLocation
cacheDir := core.QStandardPaths_WritableLocation(locType)
tmpFilename := filepath.Join(cacheDir, "users.tmp")
msgs := []string{
"Downloading user database from web sites...",
"Erasing the radio's user database...",
"Writing user database to radio...",
}
msgIndex := 0
if !download {
msgIndex = 1
}
filename := userdbFilename()
os.MkdirAll(filepath.Dir(filename), os.ModeDir|0755)
pd := ui.NewProgressDialog(msgs[msgIndex])
pd.SetRange(userdb.MinProgress, userdb.MaxProgress)
if download {
db, err := userdb.New(userdb.CuratedUsers(), userdb.Abbreviate(true))
if err != nil {
title := fmt.Sprintf("Download of user database failed")
ui.ErrorPopup(title, err.Error())
return
}
db.SetProgressCallback(func(cur int) error {
if cur == userdb.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return errors.New("cancelled")
}
return nil
})
err = db.WriteMD380ToolsFile(tmpFilename)
if err != nil {
os.Remove(tmpFilename)
pd.Close()
title := fmt.Sprintf("Download of user database failed")
ui.ErrorPopup(title, err.Error())
return
}
os.Rename(tmpFilename, filename)
}
pd.SetRange(dfu.MinProgress, dfu.MaxProgress)
df, err := dfu.New(func(cur int) error {
if cur == dfu.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return errors.New("cancelled")
}
return nil
})
if err == nil {
defer df.Close()
db, err := userdb.New(userdb.FromFile(filename), userdb.Abbreviate(true))
if err == nil {
err = df.WriteMD380Users(db)
}
}
if err != nil {
pd.Close()
title := fmt.Sprintf("write of user database failed: %s", err.Error())
ui.ErrorPopup(title, err.Error())
}
}
func writeExpandedUsers(title, text string) {
cancel, download := userdbDialog(title, text)
if cancel {
return
}
locType := core.QStandardPaths__CacheLocation
cacheDir := core.QStandardPaths_WritableLocation(locType)
tmpFilename := filepath.Join(cacheDir, "users.tmp")
msgs := []string{
"Downloading user database from web sites...",
"Preparing to write user database to radio...",
"Erasing the radio's user database...",
"Writing user database to radio...",
}
msgIndex := 0
if !download {
msgIndex = 1
}
filename := userdbFilename()
os.MkdirAll(filepath.Dir(filename), os.ModeDir|0755)
pd := ui.NewProgressDialog(msgs[msgIndex])
pd.SetRange(userdb.MinProgress, userdb.MaxProgress)
if download {
db, err := userdb.New(userdb.CuratedUsers(), userdb.Abbreviate(false))
if err != nil {
title := fmt.Sprintf("Download of user database failed")
ui.ErrorPopup(title, err.Error())
return
}
db.SetProgressCallback(func(cur int) error {
if cur == userdb.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return errors.New("cancelled")
}
return nil
})
err = db.WriteMD380ToolsFile(tmpFilename)
if err != nil {
os.Remove(tmpFilename)
pd.Close()
title := fmt.Sprintf("Download of user database failed")
ui.ErrorPopup(title, err.Error())
return
}
os.Rename(tmpFilename, filename)
}
pd.SetRange(dfu.MinProgress, dfu.MaxProgress)
df, err := dfu.New(func(cur int) error {
if cur == dfu.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return errors.New("cancelled")
}
return nil
})
if err == nil {
defer df.Close()
if err == nil {
db, err := userdb.New(userdb.FromFile(filename), userdb.Abbreviate(false))
if err == nil {
err = df.WriteUV380Users(db)
}
}
}
if err != nil {
pd.Close()
title := fmt.Sprintf("write of user database failed: %s", err.Error())
ui.ErrorPopup(title, err.Error())
}
}
func writeMD2017Users() {
title := "Write user database to radio"
text := `
The users database contains DMR ID numbers and callsigns of all registered
users. It can only be be written to MD-2017 radios.
WARNING: This only works on MD-2017 radios with the "CSV" firmware versions.`
writeExpandedUsers(title, text)
}
func writeUV380Users() {
title := "Write user database to radio"
text := `
The users database contains DMR ID numbers and callsigns of all registered
users. It can only be be written to MD-UV380 radios.
WARNING: This only works on MD-UV380 radios with the "CSV" firmware versions.`
writeExpandedUsers(title, text)
}
func factoryFirmwareDialog(modelURLs []modelURL) {
model, url := modelURLs[0].model, modelURLs[0].url
if len(modelURLs) > 1 {
title := "Write factory firmware to radio..."
upgrade := false
var canceled bool
canceled, model, url = firmwareDialog(title, modelURLs, upgrade)
if canceled {
return
}
}
msgs := []string{
fmt.Sprintf("Downloading factory %s firmware...\n%s", model, url),
"Erasing the radio's firmware...",
fmt.Sprintf("Writing factory %s firmware to radio...", model),
}
writeFirmware(url, msgs)
}
func (edt *editor) addRadioMenu(menu *ui.Menu) {
cp := edt.codeplug
mb := edt.mainWindow.MenuBar()
menu = mb.AddMenu("Radio")
menu.AddAction("Read codeplug from radio", func() {
err := codeplug.RadioExists()
if err != nil {
title := "Read codeplug from radio failed"
ui.ErrorPopup(title, err.Error())
return
}
edt := newEditor(edt.app, codeplug.FileTypeNew, "")
if edt == nil || edt.codeplug == nil {
return
}
cp := edt.codeplug
msgs := []string{
"Preparing to read codeplug from radio...",
"Reading codeplug from radio...",
}
msgIndex := 0
pd := ui.NewProgressDialog(msgs[msgIndex])
pd.SetRange(codeplug.MinProgress, codeplug.MaxProgress)
err = cp.ReadRadio(func(cur int) error {
if cur == codeplug.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return errors.New("cancelled")
}
return nil
})
if err != nil {
pd.Close()
title := "Read codeplug from radio failed"
ui.ErrorPopup(title, err.Error())
edt.FreeCodeplug()
}
if !cp.Valid() {
fmtStr := `
%d records with invalid field values were found in the codeplug.
Select "Menu->Edit->Show Invalid Fields" to view them.`
msg := fmt.Sprintf(fmtStr, len(cp.Warnings()))
ui.InfoPopup("codeplug warning", msg)
}
edt.updateMenuBar()
})
menu.AddAction("Write codeplug to radio", func() {
valid := cp.Valid()
edt.updateMenuBar()
if !valid {
fmtStr := `
%d records with invalid field values were found in the codeplug.
Click on Cancel and then select "Menu->Edit->Show Invalid Fields" to view them.
Or, click on Ignore to continue writing to the radio.`
msg := fmt.Sprintf(fmtStr, len(cp.Warnings()))
title := "write warning"
rv := ui.WarningPopup(title, msg)
if rv != ui.PopupIgnore {
return
}
}
title := "Write codeplug to radio"
model := codeplug.ModelTypes(cp.Model())
freq := cp.FrequencyRange()
warn := `
WARNING: Corruption may occur if a signal is received
while writing to the radio. The radio should be tuned
to an unprogrammed (or at least quiet) channel while
writing the new codeplug.`
msg := fmt.Sprintf("%s\n\nWrite %s %s codeplug to radio?\n", warn, model, freq)
if ui.YesNoPopup(title, msg) != ui.PopupYes {
return
}
msgs := []string{
"Preparing to write codeplug to radio...",
"Erasing the radio's codeplug...",
"Writing codeplug to radio...",
}
msgIndex := 0
pd := ui.NewProgressDialog(msgs[msgIndex])
pd.SetRange(codeplug.MinProgress, codeplug.MaxProgress)
err := cp.WriteRadio(func(cur int) error {
if cur == codeplug.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return errors.New("cancelled")
}
return nil
})
if err != nil {
pd.Close()
title := "Write codeplug to radio failed"
ui.ErrorPopup(title, err.Error())
}
}).SetEnabled(cp != nil && cp.Loaded())
menu.AddSeparator()
fwMenu := menu.AddMenu("Write factory firmware to radio...")
fwMenu.AddAction("Write MD-380 factory firmware...", func() {
dir := "https://farnsworth.org/dale/dmr/factory_firmware/md380/"
modelURLs := []modelURL{
modelURL{"MD-380 old (D03.20)", dir + "D003.020.bin"},
modelURL{"MD-380 (D13.20)", dir + "D013.020.bin"},
modelURL{"MD-380 new (D13.34)", dir + "D013.034.bin"},
modelURL{"MD-380 newer (D14.04", dir + "D014.004.bin"},
modelURL{"MD-380 newest (D15.01", dir + "D015.001.bin"},
modelURL{"MD-380G (S13.20)", dir + "S013.020.bin"},
}
factoryFirmwareDialog(modelURLs)
})
fwMenu.AddAction("Write MD-390 factory firmware...", func() {
dir := "https://farnsworth.org/dale/dmr/factory_firmware/md390/"
modelURLs := []modelURL{
modelURL{"MD-390 (D13.20)", dir + "D013.020.bin"},
modelURL{"MD-390G (S13.20)", dir + "S013.020.bin"},
}
factoryFirmwareDialog(modelURLs)
})
fwMenu.AddAction("Write RT3 factory firmware", func() {
dir := "https://farnsworth.org/dale/dmr/factory_firmware/rt3/"
modelURLs := []modelURL{
modelURL{"RT3 (D03.20)", dir + "D003.020.bin"},
}
factoryFirmwareDialog(modelURLs)
})
fwMenu.AddAction("Write RT8 factory firmware", func() {
dir := "https://farnsworth.org/dale/dmr/factory_firmware/rt8/"
modelURLs := []modelURL{
modelURL{"RT8 (S13.20)", dir + "S013.020.bin"},
}
factoryFirmwareDialog(modelURLs)
})
/*
fwMenu.AddAction("Write MD-UV380 factory firmware...", func() {
dir := "https://farnsworth.org/dale/dmr/factory_firmware/uv380/"
modelURLs := []modelURL{
modelURL{"MD-UV380 REC (D17.05)", dir + "MD-UV380(REC)-D17.05.bin"},
modelURL{"MD-UV380 CSV (V17.05)", dir + "MD-UV380(CSV)-V17.05.bin"},
}
factoryFirmwareDialog(modelURLs)
})
fwMenu.AddAction("Write MD-UV390 factory firmware...", func() {
dir := "https://farnsworth.org/dale/dmr/factory_firmware/uv390/"
modelURLs := []modelURL{
modelURL{"MD-UV390 GPS-REC (S17.05)", dir + "MD-UV390(GPS-REC)-S17.05.bin"},
modelURL{"MD-UV390 GPS-CSV (P17.05)", dir + "MD-UV390(CSV-GPS)-P17.05.bin"},
}
factoryFirmwareDialog(modelURLs)
})
*/
menu.AddSeparator()
writeUsersMenu := menu.AddMenu("Write user database to radio...")
writeUsersMenu.AddAction("Write md380tools user database to radio...", writeMD380toolsUsers)
writeUsersMenu.AddAction("Write MD2017 user database to radio...", writeMD2017Users)
writeUsersMenu.AddAction("Write MD-UV380 user database to radio...", writeUV380Users)
menu.AddSeparator()
md380toolsMenu := menu.AddMenu("md380tools...")
md380toolsMenu.AddAction("Write user database to radio...", writeMD380toolsUsers)
md380toolsMenu.AddAction("Write md380tools firmware to radio...", func() {
path := "https://farnsworth.org/dale/md380tools/firmware/"
nonGpsURL := path + "D13.20.bin"
gpsURL := path + "S13.20.bin"
modelURLs := []modelURL{
modelURL{"MD-380 (D13.20)", nonGpsURL},
modelURL{"MD-380G (S13.20)", gpsURL},
modelURL{"MD-390 (D13.20)", nonGpsURL},
modelURL{"MD-390G (S13.20)", gpsURL},
modelURL{"RT3 (D13.20)", nonGpsURL},
modelURL{"RT8 (S13.20)", gpsURL},
}
title := "Write md380tools firmware to radio..."
upgrade := true
canceled, model, url := firmwareDialog(title, modelURLs, upgrade)
if canceled {
return
}
msgs := []string{
fmt.Sprintf("Downloading md380tools %s firmware...\n%s", model, url),
"Erasing the radio's firmware...",
fmt.Sprintf("Writing md380tools %s firmware to radio...", model),
}
writeFirmware(url, msgs)
})
md380toolsMenu.AddAction("Write KD4Z md380tools firmware to radio...", func() {
path := "https://farnsworth.org/dale/md380tools/kd4z/"
nonGpsURL := path + "firmware-noGPS.bin"
gpsURL := path + "firmware-GPS.bin"
modelURLs := []modelURL{
modelURL{"MD-380 (D13.20)", nonGpsURL},
modelURL{"MD-380G (S13.20)", gpsURL},
modelURL{"MD-390 (D13.20)", nonGpsURL},
modelURL{"MD-390G (S13.20)", gpsURL},
modelURL{"RT3 (D13.20)", nonGpsURL},
modelURL{"RT8 (S13.20)", gpsURL},
}
title := "Write KD4Z md380tools firmware to radio..."
upgrade := true
canceled, model, url := firmwareDialog(title, modelURLs, upgrade)
if canceled {
return
}
msgs := []string{
fmt.Sprintf("Downloading KD4Z md380tools %s firmware...\n%s", model, url),
"Erasing the radio's firmware...",
fmt.Sprintf("Writing KD4Z md380tools %s firmware to radio...", model),
}
writeFirmware(url, msgs)
})
}
func writeFirmware(url string, msgs []string) {
tmpFile, err := ioutil.TempFile("", "editcp")
if err != nil {
title := fmt.Sprintf("temporary file failed: %s", err.Error())
ui.ErrorPopup(title, err.Error())
return
}
filename := tmpFile.Name()
defer os.Remove(filename)
msgIndex := 0
pd := ui.NewProgressDialog(msgs[msgIndex])
pd.SetRange(dfu.MinProgress, dfu.MaxProgress)
df, err := dfu.New(func(cur int) error {
if cur == dfu.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return errors.New("cancelled")
}
return nil
})
if err != nil {
pd.Close()
title := "firmware write failed"
ui.ErrorPopup(title, err.Error())
return
}
defer df.Close()
pd.SetRange(userdb.MinProgress, userdb.MaxProgress)
err = download(url, filename, func(cur int) bool {
if cur == dfu.MinProgress {
pd.SetLabelText(msgs[msgIndex])
msgIndex++
}
pd.SetValue(cur)
if pd.WasCanceled() {
return false
}
return true
})
if err != nil {
pd.Close()
title := "firmware write failed"
ui.ErrorPopup(title, err.Error())
return
}
file, err := os.Open(filename)
if err != nil {
l.Fatalf("writeFirmware: %s", err.Error())
}
defer file.Close()
err = df.WriteFirmware(file)
if err != nil {
pd.Close()
title := "write of new firmware failed"
ui.ErrorPopup(title, err.Error())
return
}
msg := "Turn radio off and back on again."
ui.InfoPopup("Firmware write complete", msg)
}
func userdbFilename() string {
locType := core.QStandardPaths__CacheLocation
cacheDir := core.QStandardPaths_WritableLocation(locType)
name := "usersDB.bin"
return filepath.Join(cacheDir, name)
}
func userdbDialog(title string, labelText string) (canceled, download bool) {
loadSettings()
usersFilename := userdbFilename()
download = true
if fileYounger(usersFilename, 12*time.Hour) {
download = false
}
downloadCheckbox := ui.NewCheckboxWidget(download, func(checked bool) {
download = checked
})
downloadCheckbox.SetEnabled(fileExists(usersFilename))
dialog := ui.NewDialog(title)
filenameBox := ui.NewHbox()
filenameBox.AddLabel(" " + usersFilename)
dialog.AddLabel(labelText[1:])
form := dialog.AddForm()
form.AddRow("Download new users database file", downloadCheckbox)
dialog.AddLabel("Filename:")
dialog.AddExistingHbox(filenameBox)
row := dialog.AddHbox()
cancelButton := ui.NewButtonWidget("Cancel", func() {
dialog.Reject()
})
row.AddWidget(cancelButton)
saveButton := ui.NewButtonWidget("Write", func() {
dialog.Accept()
})
row.AddWidget(saveButton)
saved := dialog.Exec()
return !saved, download
}
func firmwareDialog(title string, modelURLs []modelURL, upgrade bool) (canceled bool, model, url string) {
models := make([]string, len(modelURLs))
for i, modelURL := range modelURLs {
models[i] = modelURL.model
}
model = models[0]
modelCombobox := ui.NewComboboxWidget(model, models, func(index int) {
if index < 0 {
return
}
model = models[index]
})
dialog := ui.NewDialog(title)
var labelText string
if upgrade {
labelText += `
The md380tools firmware only works on MD380, MD380, RT3, and RT8 radios.`
}
labelText += `
Before continuing, enable bootloader mode:
1. Insert a cable into USB.
2. Connect the cable to the radio.
3. Power-on the radio by turning volume knob, while holding down
the PTT button and the button above PTT.
While in bootloader mode, the LED will flash green and red.`
if !upgrade {
labelText += `
Hint: If the display becomes flipped on the md380, try another
md380 variant.`
}
dialog.AddLabel(labelText[1:])
groupBox := dialog.AddGroupbox("Select Radio Model")
form := groupBox.AddForm()
form.AddRow("Radio model", modelCombobox)
row := dialog.AddHbox()
cancelButton := ui.NewButtonWidget("Cancel", func() {
dialog.Reject()
})
row.AddWidget(cancelButton)
saveButton := ui.NewButtonWidget("Update Firmware", func() {
dialog.Accept()
})
row.AddWidget(saveButton)
saved := dialog.Exec()
for _, modelURL := range modelURLs {
if modelURL.model == model {
url = modelURL.url
break
}
}
return !saved, model, url
}
var timeoutSeconds = 20
var tr = &http.Transport{
TLSHandshakeTimeout: time.Duration(timeoutSeconds) * time.Second,
ResponseHeaderTimeout: time.Duration(timeoutSeconds) * time.Second,
}
var client = &http.Client{
Transport: tr,
Timeout: time.Duration(timeoutSeconds) * time.Second,
}
type downloader struct {
url string
filename string
progressCallback func(progressCounter int) bool
progressFunc func() error
progressIncrement int
progressCounter int
}
func newDownloader() *downloader {
d := &downloader{
progressFunc: func() error { return nil },
}
return d
}
func (d *downloader) setMaxProgressCount(max int) {
d.progressFunc = func() error { return nil }
if d.progressCallback != nil {
d.progressIncrement = MaxProgress / max
d.progressCounter = 0
d.progressFunc = func() error {
d.progressCounter += d.progressIncrement
curProgress := d.progressCounter
if curProgress > MaxProgress {
curProgress = MaxProgress
}
if !d.progressCallback(d.progressCounter) {
return errors.New("")
}
return nil
}
d.progressCallback(d.progressCounter)
}
}
func (d *downloader) finalProgress() {
//fmt.Fprintf(os.Stderr, "\nprogressMax %d\n", d.progressCounter/d.progressIncrement)
if d.progressCallback != nil {
d.progressCallback(MaxProgress)
}
}
// Minimum and maximum progress values
const (
MinProgress = 0
MaxProgress = 1000000
)
func download(url, filename string, progress func(cur int) bool) error {
d := newDownloader()
d.url = url
d.filename = filename
d.progressCallback = progress
return d.download()
}
func (d *downloader) download() (err error) {
file, err := os.Create(d.filename)
if err != nil {
return wrapError("download", err)
}
defer func() {
fErr := file.Close()
if err == nil {
err = fErr
}
return
}()
resp, err := client.Get(d.url)
if err != nil {
return wrapError("download", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return wrapError("download", errors.New(resp.Status))
}
length := resp.ContentLength
if length < 0 {
length = 1024 * 1024
}
bufSize := 16 * 1024
d.setMaxProgressCount(int(length) / bufSize)
buf := make([]byte, bufSize)
for {
err := d.progressFunc()
if err != nil {
return wrapError("download", err)
}
n, err := resp.Body.Read(buf)
if n == 0 && err != nil {
if err == io.EOF {
break
}
return wrapError("download", err)
}
n, err = file.Write(buf)
if err != nil {
return wrapError("download", err)
}
}
d.finalProgress()
return nil
}
func wrapError(prefix string, err error) error {
if err.Error() == "" {
return err
}
return fmt.Errorf("%s: %s", prefix, err.Error())
}
func fileExists(filename string) bool {
_, err := os.Stat(filename)
return err == nil
}
func fileYounger(filename string, duration time.Duration) bool {
fileInfo, err := os.Stat(filename)
return err == nil && time.Since(fileInfo.ModTime()) < duration
}