-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathwalltaker.go
More file actions
909 lines (801 loc) · 26 KB
/
walltaker.go
File metadata and controls
909 lines (801 loc) · 26 KB
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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"path/filepath"
"runtime"
"strconv"
"strings"
"time"
"walltaker/icon"
"github.com/gen2brain/beeep"
"github.com/getlantern/systray"
"github.com/guregu/null"
"github.com/hugolgst/rich-go/client"
"github.com/juju/fslock"
"github.com/kardianos/osext"
"github.com/martinlindhe/inputbox"
"github.com/pelletier/go-toml"
"github.com/pkg/browser"
"github.com/potato2003/actioncable-client-go"
"github.com/reujab/wallpaper"
)
type Pref struct {
setterName string
saveLocally bool
notifications bool
oldWallpaperUrl string
}
func (p *Pref) setSetterName(newSetterName string) {
fmt.Println("CALLED setSetterName()")
fmt.Println(newSetterName)
p.setterName = newSetterName
}
func (p *Pref) setSaveLocally(newSaveLocally bool) {
fmt.Println("CALLED setSaveLocally()")
fmt.Println(newSaveLocally)
p.saveLocally = newSaveLocally
}
func (p *Pref) setNotifications(newNotifications bool) {
fmt.Println("CALLED setNotifications()")
fmt.Println(newNotifications)
p.notifications = newNotifications
}
func (p *Pref) setOldWallpaperUrl(newOldWallpaperUrl string) {
fmt.Println("CALLED setOldWallpaperUrl()")
fmt.Println(newOldWallpaperUrl)
p.oldWallpaperUrl = newOldWallpaperUrl
}
var pref Pref
var setterName string = ""
var menuAppSetBy *systray.MenuItem = systray.AddMenuItem("-", "Who sent your most recent wallpaper~")
var saveLocally bool = false
var notifications bool = false
type LinkSubscriptionEventHandler struct {
actioncable.SubscriptionEventHandler
}
func (h *LinkSubscriptionEventHandler) OnConnected(se *actioncable.SubscriptionEvent) {
fmt.Println("on connected")
}
func (h *LinkSubscriptionEventHandler) OnDisconnected(se *actioncable.SubscriptionEvent) {
fmt.Println("on disconnected")
}
func (h *LinkSubscriptionEventHandler) OnRejected(se *actioncable.SubscriptionEvent) {
fmt.Println("on rejected")
}
func (h *LinkSubscriptionEventHandler) OnReceived(se *actioncable.SubscriptionEvent) {
userData := WalltakerData{}
se.ReadJSON(&userData)
wallpaperUrl := userData.PostURL.String
log.Println("New Image... ")
if wallpaperUrl != pref.oldWallpaperUrl {
pref.setSetterName(userData.SetBy.String)
setterName = userData.SetBy.String
setAt := strings.ReplaceAll(time.Now().Format(time.RFC3339), ":", "-")
if setterName != "" {
log.Printf(setterName)
log.Printf(" set your wallpaper! Setting... ")
menuAppSetBy.SetTitle(fmt.Sprintf("Set by %s", setterName))
} else {
log.Printf("New wallpaper found! Setting... ")
menuAppSetBy.SetTitle(fmt.Sprintf("Set by %s", "Anonymous"))
}
pref.setOldWallpaperUrl(wallpaperUrl)
goSetWallpaper(wallpaperUrl, saveLocally, setterName, setAt, notifications)
log.Printf("Set!")
log.Printf("\r\n")
}
}
var VERSION string = "v2.1.0"
type WalltakerData struct {
ID int `json:"id"`
Expires time.Time `json:"expires"`
UserID int `json:"user_id"`
Terms string `json:"terms"`
Blacklist string `json:"blacklist"`
PostURL null.String `json:"post_url"`
PostThumbnailURL interface{} `json:"post_thumbnail_url"`
PostDescription interface{} `json:"post_description"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
SetBy null.String `json:"set_by"`
URL string `json:"url"`
}
type E621PostsData struct {
Posts []struct {
ID int `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
File struct {
Width int `json:"width"`
Height int `json:"height"`
Ext string `json:"ext"`
Size int `json:"size"`
Md5 string `json:"md5"`
URL string `json:"url"`
} `json:"file"`
Preview struct {
Width int `json:"width"`
Height int `json:"height"`
URL string `json:"url"`
} `json:"preview"`
Sample struct {
Has bool `json:"has"`
Height int `json:"height"`
Width int `json:"width"`
URL string `json:"url"`
Alternates struct {
} `json:"alternates"`
} `json:"sample"`
Score struct {
Up int `json:"up"`
Down int `json:"down"`
Total int `json:"total"`
} `json:"score"`
Tags struct {
General []string `json:"general"`
Species []string `json:"species"`
Character []string `json:"character"`
Copyright []string `json:"copyright"`
Artist []string `json:"artist"`
Invalid []interface{} `json:"invalid"`
Lore []interface{} `json:"lore"`
Meta []string `json:"meta"`
} `json:"tags"`
LockedTags []interface{} `json:"locked_tags"`
ChangeSeq int `json:"change_seq"`
Flags struct {
Pending bool `json:"pending"`
Flagged bool `json:"flagged"`
NoteLocked bool `json:"note_locked"`
StatusLocked bool `json:"status_locked"`
RatingLocked bool `json:"rating_locked"`
Deleted bool `json:"deleted"`
} `json:"flags"`
Rating string `json:"rating"`
FavCount int `json:"fav_count"`
Sources []string `json:"sources"`
Pools []interface{} `json:"pools"`
Relationships struct {
ParentID interface{} `json:"parent_id"`
HasChildren bool `json:"has_children"`
HasActiveChildren bool `json:"has_active_children"`
Children []interface{} `json:"children"`
} `json:"relationships"`
ApproverID int `json:"approver_id"`
UploaderID int `json:"uploader_id"`
Description string `json:"description"`
CommentCount int `json:"comment_count"`
IsFavorited bool `json:"is_favorited"`
HasNotes bool `json:"has_notes"`
Duration interface{} `json:"duration"`
} `json:"posts"`
}
func getWalltakerData(url string) WalltakerData {
webClient := http.Client{
Timeout: time.Second * 2, // Timeout after 2 seconds
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", "Walltaker Go Client/"+VERSION+"-"+runtime.GOOS)
res, getErr := webClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
if res.Body != nil {
defer res.Body.Close()
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
userData := WalltakerData{}
jsonErr := json.Unmarshal(body, &userData)
if jsonErr != nil {
log.Fatal(jsonErr)
}
return userData
}
type NoDataError struct {
IntA int
IntB int
Msg string
}
func (e *NoDataError) Error() string {
return e.Msg
}
func getWallpaperUrlFromData(userData WalltakerData) (string, error) {
if userData.PostURL.String == "" {
return "", &NoDataError{
Msg: fmt.Sprintf("No data found for ID %d", userData.ID),
}
}
return userData.PostURL.String, nil
}
func clearWindowsWallpaperCache() {
// Remove cached wallpaper files, issue #12
if runtime.GOOS == "windows" {
windowsWallpaperCacheDir := os.Getenv("APPDATA") + "\\Microsoft\\Windows\\Themes"
if _, err := os.Stat(windowsWallpaperCacheDir + "\\TranscodedWallpaper"); !os.IsNotExist(err) {
e := os.Remove(windowsWallpaperCacheDir + "\\TranscodedWallpaper")
if e != nil {
log.Fatal(e)
}
}
if _, err2 := os.Stat(windowsWallpaperCacheDir + "\\CachedFiles"); !os.IsNotExist(err2) {
e2 := os.RemoveAll(windowsWallpaperCacheDir + "\\CachedFiles")
if e2 != nil {
log.Fatal(e2)
}
}
}
}
func goSetWallpaper(url string, saveLocally bool, setterName string, setAt string, notify bool) {
clearWindowsWallpaperCache()
if runtime.GOOS != "windows" {
file, err := downloadImageForMac(url)
if err != nil {
log.Println("Ouch! Had a problem while downloading your wallpaper. This is a mac specific bug!")
log.Println("Full error: ", err)
}
wallpaper.SetFromFile(file)
defer cleanUpCacheForMac(file) // OK to delete after setting wallpaper, MacOS shows bg w/o file remaining there
} else {
err := wallpaper.SetFromURL(getImageUrlWithAppropriateSize(url))
if err != nil {
log.Println("Ouch! Had a problem while setting your wallpaper.")
log.Println("Full error: ", err)
}
}
if notify {
notifyStr := ""
if setterName == "" {
notifyStr = "Someone changed your wallpaper~"
} else {
notifyStr = fmt.Sprintf("%s changed your wallpaper~", setterName)
}
errNotify := beeep.Notify("Walltaker", notifyStr, "")
if errNotify != nil {
panic(errNotify)
}
}
if saveLocally {
saveWallpaperLocally(url, setterName, setAt)
}
return
}
func saveWallpaperLocally(url string, setterName string, setAt string) {
if setterName == "" {
setterName = "anonymous"
}
folderPath, err := osext.ExecutableFolder()
_, err = os.Stat(filepath.Join(folderPath, "download"))
if os.IsNotExist(err) {
log.Println("Created download directory since it did not exist")
os.Mkdir(filepath.Join(folderPath, "download"), os.FileMode(0777))
}
filename := filepath.Join(folderPath, "download", "walltaker_"+setterName+"_"+setAt+"_"+path.Base(url))
_, err = os.Stat(filename)
if os.IsNotExist(err) {
//log.Printf("Downloading", url, " to ", filename)
response, err := http.Get(url)
if err != nil {
return
}
defer response.Body.Close()
file, err := os.Create(filename)
if err != nil {
return
}
defer file.Close()
_, err = io.Copy(file, response.Body)
} else {
log.Printf("Wallpaper file already exists, skipping! ")
}
return
}
func openMyWtWebAppLink(base string, feed int64) {
browser.OpenURL(fmt.Sprintf("%s%d", base, feed))
}
func openWtSetterPage(setterName string) {
if setterName != "" {
browser.OpenURL(fmt.Sprintf("https://walltaker.joi.how/users/%s", setterName))
}
}
func extractMD5(url string) string {
if url != "" {
md5str := url[strings.LastIndex(url, "/")+1:]
md5str = strings.Split(md5str, ".")[0]
return md5str
}
return ""
}
func formatE621SearchByMD5(md5 string) string {
return fmt.Sprintf("https://e621.net/posts?tags=md5%%3A%s", md5)
}
func formatE621APISearchByMD5(md5 string) string {
return fmt.Sprintf("https://e621.net/posts.json?tags=md5%%3A%s", md5)
}
func openE621(postUrl string) {
// extract md5 from post url
if postUrl != "" {
e621Posts := getE621Data(postUrl)
if len(e621Posts.Posts) > 0 {
browser.OpenURL(fmt.Sprintf("https://e621.net/posts/%d", e621Posts.Posts[0].ID))
}
// md5url := formatE621SearchByMD5(extractMD5(postUrl))
// browser.OpenURL(md5url)
}
}
func getE621Data(postUrl string) E621PostsData {
// extract md5 from post url
if postUrl != "" {
postsDataUrl := formatE621APISearchByMD5(extractMD5(postUrl))
// get json data from url
webClient := http.Client{
Timeout: time.Second * 2, // Timeout after 2 seconds
}
req, err := http.NewRequest(http.MethodGet, postsDataUrl, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("User-Agent", "Walltaker Go Client/"+VERSION+"-"+runtime.GOOS)
res, getErr := webClient.Do(req)
if getErr != nil {
log.Fatal(getErr)
}
if res.Body != nil {
defer res.Body.Close()
}
body, readErr := ioutil.ReadAll(res.Body)
if readErr != nil {
log.Fatal(readErr)
}
postsData := E621PostsData{}
jsonErr := json.Unmarshal(body, &postsData)
if jsonErr != nil {
log.Fatal(jsonErr)
}
return postsData
}
return E621PostsData{}
}
func getImageUrlWithAppropriateSize(postUrl string) string {
if postUrl != "" {
postsData := getE621Data(postUrl)
if len(postsData.Posts) > 0 {
if postsData.Posts[0].File.Size > 17000000 {
return postsData.Posts[0].Sample.URL
} else {
return postsData.Posts[0].File.URL
}
}
}
return ""
}
func performVersionCheck() {
// get latest version tag from Github
resp, err := http.Get("https://api.github.com/repos/PawCorp/walltaker-desktop-client/releases/latest")
if err != nil {
log.Println("Failed to check for updates: ", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("Failed to read response: ", err)
return
}
// parse response
var latestRelease struct {
TagName string `json:"tag_name"`
}
json.Unmarshal(body, &latestRelease)
// compare versions
if latestRelease.TagName != VERSION {
log.Println("A new version of Walltaker is available!")
log.Println("Current:", VERSION, "Latest:", latestRelease.TagName)
log.Println("You can download it from ", "https://github.com/PawCorp/walltaker-desktop-client/releases/latest")
errNotify := beeep.Notify("Walltaker", "A new version of Walltaker is available! Please visit https://q.pawcorp.org/wtgo to download.", "")
if errNotify != nil {
panic(errNotify)
}
}
}
func main() {
// log to file
fn := logOutput()
defer fn()
// use file lock to determine if walltaker is already running
lockPath := "./walltaker.lock"
if runtime.GOOS == "darwin" {
lockPath = "/tmp/walltaker.lock"
}
lock := fslock.New(lockPath)
err := lock.TryLock()
if err != nil {
log.Println(err.Error())
errNotify := beeep.Notify("Walltaker", "Note: Walltaker is already running!", "")
if errNotify != nil {
panic(errNotify)
}
return
}
bg, err := wallpaper.Get()
if err != nil {
panic(err)
}
log.Println("Detected original wallpaper as: ", bg)
defer lock.Unlock()
onExit := func() {
log.Println("Reverting wallpaper to: ", bg)
wallpaper.SetFromFile(bg)
}
systray.Run(onReady, onExit)
}
func onReady() {
// log.Println("WALLTAKER CLIENT")
log.Println(`
██╗ ██╗ █████╗ ██╗ ██╗ ████████╗ █████╗ ██╗ ██╗███████╗██████╗
██║ ██║██╔══██╗██║ ██║ ╚══██╔══╝██╔══██╗██║ ██╔╝██╔════╝██╔══██╗
██║ █╗ ██║███████║██║ ██║ ██║ ███████║█████╔╝ █████╗ ██████╔╝
██║███╗██║██╔══██║██║ ██║ ██║ ██╔══██║██╔═██╗ ██╔══╝ ██╔══██╗
╚███╔███╔╝██║ ██║███████╗███████╗██║ ██║ ██║██║ ██╗███████╗██║ ██║
╚══╝╚══╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
` + VERSION + `. Go client by @OddPawsX
Walltaker by Gray over at joi.how <3
(You can minimize this window; it will periodically check in for new wallpapers)
`)
performVersionCheck()
start := time.Now()
folderPath, err := osext.ExecutableFolder()
if err != nil {
log.Fatal(err)
}
dat, err := os.ReadFile(filepath.Join(folderPath, "walltaker.toml"))
if err != nil {
log.Fatal(err)
}
log.Println("Loaded config from " + filepath.Join(folderPath, "walltaker.toml"))
tomlDat := string(dat)
config, _ := toml.Load(tomlDat)
defer func() {
if r := recover(); r != nil {
log.Println("Ensure your .toml file is up to date!")
errNotify := beeep.Notify("Walltaker", "Could not launch Walltaker! Ensure your .toml file is up to date.", "")
if errNotify != nil {
panic(errNotify)
}
systray.Quit()
}
}()
// store crop bool
crop := true // true before read in by config
base := config.Get("Base.base").(string)
feed := config.Get("Feed.feed").(int64)
mode := config.Get("Preferences.mode").(string)
saveLocally = config.Get("Preferences.saveLocally").(bool)
useDiscord := config.Get("Preferences.discordPresence").(bool)
notifications = config.Get("Preferences.notifications").(bool)
if strings.ToLower(mode) == "fit" {
crop = false
} else if strings.ToLower(mode) == "crop" {
crop = true
} else {
crop = true
}
builtUrl := base + strconv.FormatInt(feed, 10) + ".json"
timeNow := time.Now() // start time for discord purposes
if useDiscord == true {
discorderr := client.Login("942796233033019504")
if discorderr != nil {
log.Fatal(discorderr)
}
discorderr = client.SetActivity(client.Activity{
State: "Set my wallpaper~",
// Details: strings.Replace(builtUrl, ".json", "", -1),
Details: fmt.Sprintf("https://wt.pawcorp.org/%d", feed),
LargeImage: "eggplant",
LargeText: "Powered by joi.how",
Timestamps: &client.Timestamps{
Start: &timeNow,
},
})
if discorderr != nil {
log.Fatal(discorderr)
}
}
if saveLocally == true {
log.Println("Local saving enabled")
_, err := os.Stat(filepath.Join(folderPath, "download"))
if os.IsNotExist(err) {
log.Println("Created download directory since it did not exist")
os.Mkdir(filepath.Join(folderPath, "download"), os.FileMode(0777))
}
}
systray.SetTemplateIcon(icon.Data, icon.Data)
systray.SetTitle("Walltaker")
systray.SetTooltip("Walltaker")
menuAppTimer := systray.AddMenuItem("Elapsed: 0", "Time since Walltaker started")
menuAppTimer.SetIcon(icon.Data)
menuAppTimer.Disabled()
// menuAppSetBy := systray.AddMenuItem("-", "Who sent your most recent wallpaper~") // moved to global
menuE621 := systray.AddMenuItem("Open e621", "Open image on e621")
// menuAppSetBy.Disabled()
setterName = ""
u, _ := url.Parse("wss://walltaker.joi.how/cable")
consumer, _ := actioncable.CreateConsumer(u, nil)
consumer.Connect()
params := map[string]interface{}{
"id": feed,
}
id := actioncable.NewChannelIdentifier("LinkChannel", params)
subscription, subErr := consumer.Subscriptions.Create(id)
if subErr != nil {
log.Fatal("Failed to subscribe")
}
subscription.SetHandler(&LinkSubscriptionEventHandler{})
// timer loop
go func() {
for range time.Tick(time.Second) {
elapsed := time.Since(start)
menuAppTimer.SetTitle(fmt.Sprintf("Elapsed: %s", elapsed.Round(time.Second)))
}
}()
// wallpaper loop
go func() {
bg, err := wallpaper.Get()
if err != nil {
panic(err)
}
log.Println("Detected original wallpaper as: ", bg)
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
go func() {
<-c
wallpaper.SetFromFile(bg)
os.Exit(0)
}()
userData := getWalltakerData(builtUrl)
wallpaperUrl, noDataErr := getWallpaperUrlFromData(userData)
ready := noDataErr == nil
for ready == false {
if noDataErr != nil {
// log.Fatal(noDataErr)
time.Sleep(time.Second * time.Duration(5))
builtUrl = base + strconv.FormatInt(feed, 10) + ".json" // account for runtime change of poll ID
userData = getWalltakerData(builtUrl)
wallpaperUrl, noDataErr = getWallpaperUrlFromData(userData)
} else {
ready = true
}
}
setterName = userData.SetBy.String
setAt := strings.ReplaceAll(time.Now().Format(time.RFC3339), ":", "-")
if setterName != "" {
log.Printf(setterName)
log.Printf(" set your initial wallpaper: Setting... ")
menuAppSetBy.SetTitle(fmt.Sprintf("Set by %s", setterName))
} else {
log.Printf("Anonymous set your initial wallpaper: Setting... ")
menuAppSetBy.SetTitle(fmt.Sprintf("Set by %s", "Anonymous"))
}
goSetWallpaper(wallpaperUrl, saveLocally, setterName, setAt, notifications)
log.Printf("Set!")
if !crop {
err = wallpaper.SetMode(wallpaper.Fit)
} else if crop {
err = wallpaper.SetMode(wallpaper.Crop)
} else {
err = wallpaper.SetMode(wallpaper.Crop)
}
pref.setOldWallpaperUrl(wallpaperUrl)
}()
go func() {
menuOpenMyWtWebAppLink := systray.AddMenuItem(fmt.Sprintf("Open my Walltaker Page (%d)", feed), "Opens your link in a web browser")
systray.AddSeparator()
menuCropImages := systray.AddMenuItemCheckbox("Crop", "Crop images to fill the whole screen", crop)
menuSaveImages := systray.AddMenuItemCheckbox("Save Images", "Check to save images to disk", saveLocally)
menuDiscordPresence := systray.AddMenuItemCheckbox("Discord Presence", "Let your friends know what you're up to~", useDiscord)
menuNotifications := systray.AddMenuItemCheckbox("Notifications", "Get a desktop notification for new wallpapers, in case you've got something maximized", notifications)
menuSetID := systray.AddMenuItem("Set ID", "Change which IDs wallpaper feed to use")
systray.AddSeparator()
mQuit := systray.AddMenuItem("QUIT", "Quit the whole app")
systray.AddSeparator()
for {
select {
case <-menuE621.ClickedCh:
openE621(pref.oldWallpaperUrl)
case <-menuAppSetBy.ClickedCh:
openWtSetterPage(setterName)
case <-menuOpenMyWtWebAppLink.ClickedCh:
openMyWtWebAppLink(base, feed)
case <-menuSetID.ClickedCh:
getInputText := "Enter a Walltaker ID to poll"
for {
var i int
got, ok := inputbox.InputBox("Change active Walltaker ID", getInputText, "0")
if ok {
log.Println("you entered:", got)
} else {
log.Println("No value entered")
}
if got == "" {
log.Println(fmt.Sprintf("No value entered; keeping old value of %d", feed))
break
}
i, err = strconv.Atoi(got)
if err != nil {
log.Println("Enter a valid number")
getInputText = "Enter a Walltaker ID to poll (you entered something that was not a number last time; try again)"
} else {
log.Println("Got: " + strconv.Itoa(i))
feed = int64(i)
subscription.Unsubscribe() // unsubscribe from previous channel
params := map[string]interface{}{
"id": feed,
}
id := actioncable.NewChannelIdentifier("LinkChannel", params)
subscription, subErr := consumer.Subscriptions.Create(id)
if subErr != nil {
log.Fatal("Failed to subscribe")
}
subscription.SetHandler(&LinkSubscriptionEventHandler{})
builtUrl := base + strconv.FormatInt(feed, 10) + ".json"
userData := getWalltakerData(builtUrl)
wallpaperUrl, noDataErr := getWallpaperUrlFromData(userData)
ready := noDataErr == nil
for ready == false {
if noDataErr != nil {
// log.Fatal(noDataErr)
time.Sleep(time.Second * time.Duration(5))
builtUrl = base + strconv.FormatInt(feed, 10) + ".json" // account for runtime change of poll ID
userData = getWalltakerData(builtUrl)
wallpaperUrl, noDataErr = getWallpaperUrlFromData(userData)
} else {
ready = true
}
}
setterName = userData.SetBy.String
setAt := strings.ReplaceAll(time.Now().Format(time.RFC3339), ":", "-")
if setterName != "" {
log.Printf(setterName)
log.Printf(" set your initial wallpaper: Setting... ")
menuAppSetBy.SetTitle(fmt.Sprintf("Set by %s", setterName))
} else {
log.Printf("Anonymous set your initial wallpaper: Setting... ")
menuAppSetBy.SetTitle(fmt.Sprintf("Set by %s", "Anonymous"))
}
goSetWallpaper(wallpaperUrl, saveLocally, setterName, setAt, notifications)
log.Printf("Set!")
if !crop {
err = wallpaper.SetMode(wallpaper.Fit)
} else if crop {
err = wallpaper.SetMode(wallpaper.Crop)
} else {
err = wallpaper.SetMode(wallpaper.Crop)
}
pref.setOldWallpaperUrl(wallpaperUrl)
if useDiscord == true {
discorderr := client.SetActivity(client.Activity{
State: "Set my wallpaper~",
// Details: base + strconv.FormatInt(feed, 10),
Details: fmt.Sprintf("https://wt.pawcorp.org/%d", feed),
LargeImage: "eggplant",
LargeText: "Powered by joi.how",
Timestamps: &client.Timestamps{
Start: &timeNow,
},
})
if discorderr != nil {
log.Fatal(discorderr)
}
}
menuOpenMyWtWebAppLink.SetTitle(fmt.Sprintf("Open my Walltaker Page (%d)", feed))
log.Println("Set new Walltaker poll ID")
break
}
}
case <-menuCropImages.ClickedCh:
if menuCropImages.Checked() {
menuCropImages.Uncheck()
err = wallpaper.SetMode(wallpaper.Fit)
} else {
menuCropImages.Check()
err = wallpaper.SetMode(wallpaper.Crop)
}
crop = !crop
case <-menuSaveImages.ClickedCh:
if menuSaveImages.Checked() {
menuSaveImages.Uncheck()
} else {
menuSaveImages.Check()
}
saveLocally = !saveLocally
log.Println(fmt.Sprintf("Changed saveLocally to %t", saveLocally))
case <-menuDiscordPresence.ClickedCh:
if menuDiscordPresence.Checked() {
menuDiscordPresence.Uncheck()
client.Logout()
log.Println("Stopped Discord Presence")
} else {
menuDiscordPresence.Check()
discorderr := client.Login("942796233033019504")
if discorderr != nil {
log.Fatal(discorderr)
}
discorderr = client.SetActivity(client.Activity{
State: "Set my wallpaper~",
// Details: strings.Replace(builtUrl, ".json", "", -1),
Details: fmt.Sprintf("https://wt.pawcorp.org/%d", feed),
LargeImage: "eggplant",
LargeText: "Powered by joi.how",
Timestamps: &client.Timestamps{
Start: &timeNow,
},
})
if discorderr != nil {
log.Fatal(discorderr)
}
log.Println("Started Discord Presence")
}
useDiscord = !useDiscord
case <-menuNotifications.ClickedCh:
if menuNotifications.Checked() {
menuNotifications.Uncheck()
} else {
menuNotifications.Check()
}
notifications = !notifications
log.Println(fmt.Sprintf("notifications set to %t", notifications))
case <-mQuit.ClickedCh:
systray.Quit()
log.Println("Quit now...")
return
}
}
}()
}
func logOutput() func() {
// modified from https://gist.github.com/jerblack/4b98ba48ed3fb1d9f7544d2b1a1be287
cacheDir, err := os.UserCacheDir()
if err != nil {
panic(err)
}
wtCacheDir := filepath.Join(cacheDir, ".walltaker")
wtCacheLogsDir := filepath.Join(wtCacheDir, "logs")
if _, err := os.Stat(wtCacheDir); os.IsNotExist(err) {
err := os.Mkdir(wtCacheDir, os.FileMode(0777))
if err != nil {
panic(err)
}
}
if _, err := os.Stat(wtCacheLogsDir); os.IsNotExist(err) {
err := os.Mkdir(wtCacheLogsDir, os.FileMode(0777))
if err != nil {
panic(err)
}
}
logfile := filepath.Join(wtCacheLogsDir, "walltaker.log")
f, err := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
// defer f.Close()
log.SetOutput(f)
// log.Println("This is a test log entry")
return func() {
// close file after all writes have finished
_ = f.Close()
}
}