forked from Seklfreak/discord-image-downloader-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
1689 lines (1574 loc) · 54.7 KB
/
main.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
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"mime"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"syscall"
"time"
"os/signal"
"github.com/HouzuoGuo/tiedot/db"
"github.com/Jeffail/gabs"
"github.com/PuerkitoBio/goquery"
"github.com/bwmarrin/discordgo"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
"github.com/hashicorp/go-version"
"golang.org/x/net/context"
"golang.org/x/net/html"
"golang.org/x/oauth2/google"
"google.golang.org/api/drive/v3"
"google.golang.org/api/googleapi"
"gopkg.in/ini.v1"
"mvdan.cc/xurls"
)
var (
ChannelWhitelist map[string]string
InteractiveChannelWhitelist map[string]string
RegexpUrlTwitter *regexp.Regexp
RegexpUrlTwitterStatus *regexp.Regexp
RegexpUrlTistory *regexp.Regexp
RegexpUrlTistoryWithCDN *regexp.Regexp
RegexpUrlGfycat *regexp.Regexp
RegexpUrlInstagram *regexp.Regexp
RegexpUrlImgurSingle *regexp.Regexp
RegexpUrlImgurAlbum *regexp.Regexp
RegexpUrlGoogleDrive *regexp.Regexp
RegexpUrlGoogleDriveFolder *regexp.Regexp
RegexpUrlPossibleTistorySite *regexp.Regexp
RegexpUrlFlickrPhoto *regexp.Regexp
RegexpUrlFlickrAlbum *regexp.Regexp
RegexpUrlFlickrAlbumShort *regexp.Regexp
RegexpUrlStreamable *regexp.Regexp
dg *discordgo.Session
DownloadTistorySites bool
interactiveChannelLinkTemp map[string]string
DiscordUserId string
myDB *db.DB
historyCommandActive map[string]string
MaxDownloadRetries int
flickrApiKey string
twitterConsumerKey string
twitterConsumerSecret string
twitterAccessToken string
twitterAccessTokenSecret string
DownloadTimeout int
SendNoticesToInteractiveChannels bool
SendStatusMessages bool
clientCredentialsJson string
DriveService *drive.Service
discordstatuscfg string
)
const (
VERSION = "1.0"
DATABASE_DIR = "database"
RELEASE_URL = "https://github.com/smokeofc/discordgo-imagescraper/releases/latest"
RELEASE_API_URL = "https://api.github.com/repos/smokeofc/discordgo-imagescraper/releases/latest"
IMGUR_CLIENT_ID = "a39473314df3f59"
REGEXP_URL_TWITTER = `^http(s?):\/\/pbs(-[0-9]+)?\.twimg\.com\/media\/[^\./]+\.(jpg|png)((\:[a-z]+)?)$`
REGEXP_URL_TWITTER_STATUS = `^http(s?):\/\/(www\.)?twitter\.com\/([A-Za-z0-9-_\.]+\/status\/|statuses\/|i\/web\/status\/)([0-9]+)$`
REGEXP_URL_TISTORY = `^http(s?):\/\/[a-z0-9]+\.uf\.tistory\.com\/(image|original)\/[A-Z0-9]+$`
REGEXP_URL_TISTORY_WITH_CDN = `^http(s)?:\/\/[0-9a-z]+.daumcdn.net\/[a-z]+\/[a-zA-Z0-9\.]+\/\?scode=mtistory&fname=http(s?)%3A%2F%2F[a-z0-9]+\.uf\.tistory\.com%2F(image|original)%2F[A-Z0-9]+$`
REGEXP_URL_GFYCAT = `^http(s?):\/\/gfycat\.com\/(gifs\/detail\/)?[A-Za-z]+$`
REGEXP_URL_INSTAGRAM = `^http(s?):\/\/(www\.)?instagram\.com\/p\/[^/]+\/(\?[^/]+)?$`
REGEXP_URL_IMGUR_SINGLE = `^http(s?):\/\/(i\.)?imgur\.com\/[A-Za-z0-9]+(\.gifv)?$`
REGEXP_URL_IMGUR_ALBUM = `^http(s?):\/\/imgur\.com\/(a\/|gallery\/|r\/[^\/]+\/)[A-Za-z0-9]+(#[A-Za-z0-9]+)?$`
REGEXP_URL_GOOGLEDRIVE = `^http(s?):\/\/drive\.google\.com\/file\/d\/[^/]+\/view$`
REGEXP_URL_GOOGLEDRIVE_FOLDER = `^http(s?):\/\/drive\.google\.com\/(drive\/folders\/|open\?id=)([^/]+)$`
REGEXP_URL_POSSIBLE_TISTORY_SITE = `^http(s)?:\/\/[0-9a-zA-Z\.-]+\/(m\/)?(photo\/)?[0-9]+$`
REGEXP_URL_FLICKR_PHOTO = `^http(s)?:\/\/(www\.)?flickr\.com\/photos\/([0-9]+)@([A-Z0-9]+)\/([0-9]+)(\/)?(\/in\/album-([0-9]+)(\/)?)?$`
REGEXP_URL_FLICKR_ALBUM = `^http(s)?:\/\/(www\.)?flickr\.com\/photos\/(([0-9]+)@([A-Z0-9]+)|[A-Za-z0-9]+)\/(albums\/(with\/)?|(sets\/)?)([0-9]+)(\/)?$`
REGEXP_URL_FLICKR_ALBUM_SHORT = `^http(s)?:\/\/((www\.)?flickr\.com\/gp\/[0-9]+@[A-Z0-9]+\/[A-Za-z0-9]+|flic\.kr\/s\/[a-zA-Z0-9]+)$`
REGEXP_URL_STREAMABLE = `^http(s?):\/\/(www\.)?streamable\.com\/([0-9a-z]+)$`
)
type GfycatObject struct {
GfyItem map[string]string
}
type ImgurAlbumObject struct {
Data []struct {
Link string
}
}
func main() {
fmt.Printf("discordgo-imagescraper version %s\n", VERSION)
if !isLatestRelease() {
fmt.Printf("update available on %s !\n", RELEASE_URL)
}
var err error
cfg, err := ini.Load("config.ini")
if err != nil {
fmt.Println("unable to read config file", err)
cfg = ini.Empty()
}
if (!cfg.Section("auth").HasKey("email") ||
!cfg.Section("auth").HasKey("password")) &&
!cfg.Section("auth").HasKey("token") {
cfg.Section("auth").NewKey("email", "[email protected]")
cfg.Section("auth").NewKey("password", "your password")
cfg.Section("general").NewKey("skip edits", "true")
cfg.Section("general").NewKey("download tistory sites", "false")
cfg.Section("general").NewKey("max download retries", "5")
cfg.Section("general").NewKey("download timeout", "60")
cfg.Section("general").NewKey("send notices to interactive channels", "false")
cfg.Section("general").NewKey("send status messages","true")
cfg.Section("general").NewKey("discord status", "Running image scraper")
cfg.Section("channels").NewKey("channelid1", "C:\\full\\path\\1")
cfg.Section("channels").NewKey("channelid2", "C:\\full\\path\\2")
cfg.Section("channels").NewKey("channelid3", "C:\\full\\path\\3")
cfg.Section("flickr").NewKey("api key", "your flickr api key")
cfg.Section("twitter").NewKey("consumer key", "your consumer key")
cfg.Section("twitter").NewKey("consumer secret", "your consumer secret")
cfg.Section("twitter").NewKey("access token", "your access token")
cfg.Section("twitter").NewKey("access token secret", "your access token secret")
err = cfg.SaveTo("config.ini")
if err != nil {
fmt.Println("unable to write config file", err)
return
}
fmt.Println("Wrote config file, please fill out and restart the program")
return
}
myDB, err = db.OpenDB(DATABASE_DIR)
if err != nil {
fmt.Println("unable to create db", err)
return
}
if myDB.Use("Downloads") == nil {
if err := myDB.Create("Downloads"); err != nil {
fmt.Println("unable to create db", err)
return
}
if err := myDB.Use("Downloads").Index([]string{"Url"}); err != nil {
fmt.Println("unable to create index", err)
return
}
}
ChannelWhitelist = cfg.Section("channels").KeysHash()
InteractiveChannelWhitelist = cfg.Section("interactive channels").KeysHash()
interactiveChannelLinkTemp = make(map[string]string)
historyCommandActive = make(map[string]string)
flickrApiKey = cfg.Section("flickr").Key("api key").MustString("yourflickrapikey")
twitterConsumerKey = cfg.Section("twitter").Key("consumer key").MustString("your consumer key")
twitterConsumerSecret = cfg.Section("twitter").Key("consumer secret").MustString("your consumer secret")
twitterAccessToken = cfg.Section("twitter").Key("access token").MustString("your access token")
twitterAccessTokenSecret = cfg.Section("twitter").Key("access token secret").MustString("your access token secret")
RegexpUrlTwitter, err = regexp.Compile(REGEXP_URL_TWITTER)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlTwitterStatus, err = regexp.Compile(REGEXP_URL_TWITTER_STATUS)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlTistory, err = regexp.Compile(REGEXP_URL_TISTORY)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlTistoryWithCDN, err = regexp.Compile(REGEXP_URL_TISTORY_WITH_CDN)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlGfycat, err = regexp.Compile(REGEXP_URL_GFYCAT)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlInstagram, err = regexp.Compile(REGEXP_URL_INSTAGRAM)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlImgurSingle, err = regexp.Compile(REGEXP_URL_IMGUR_SINGLE)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlImgurAlbum, err = regexp.Compile(REGEXP_URL_IMGUR_ALBUM)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlGoogleDrive, err = regexp.Compile(REGEXP_URL_GOOGLEDRIVE)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlGoogleDriveFolder, err = regexp.Compile(REGEXP_URL_GOOGLEDRIVE_FOLDER)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlPossibleTistorySite, err = regexp.Compile(REGEXP_URL_POSSIBLE_TISTORY_SITE)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlFlickrPhoto, err = regexp.Compile(REGEXP_URL_FLICKR_PHOTO)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlFlickrAlbum, err = regexp.Compile(REGEXP_URL_FLICKR_ALBUM)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlStreamable, err = regexp.Compile(REGEXP_URL_STREAMABLE)
if err != nil {
fmt.Println("Regexp error", err)
return
}
RegexpUrlFlickrAlbumShort, err = regexp.Compile(REGEXP_URL_FLICKR_ALBUM_SHORT)
if err != nil {
fmt.Println("Regexp error", err)
return
}
if cfg.Section("auth").HasKey("token") {
dg, err = discordgo.New(cfg.Section("auth").Key("token").String())
} else {
dg, err = discordgo.New(
cfg.Section("auth").Key("email").String(),
cfg.Section("auth").Key("password").String())
}
if err != nil {
fmt.Println("error creating Discord session,", err)
return
}
dg.AddHandler(messageCreate)
if cfg.Section("general").HasKey("skip edits") {
if cfg.Section("general").Key("skip edits").MustBool() == false {
dg.AddHandler(messageUpdate)
}
}
DownloadTistorySites = cfg.Section("general").Key("download tistory sites").MustBool()
MaxDownloadRetries = cfg.Section("general").Key("max download retries").MustInt(3)
DownloadTimeout = cfg.Section("general").Key("download timeout").MustInt(60)
SendNoticesToInteractiveChannels = cfg.Section("general").Key("send notices to interactive channels").MustBool(false)
SendStatusMessages = cfg.Section("general").Key("send status messages").MustBool()
// discord status
discordstatuscfg = cfg.Section("general").Key("discord status").MustString("")
// setup google drive client
clientCredentialsJson = cfg.Section("google").Key("client credentials json").MustString("")
if clientCredentialsJson != "" {
ctx := context.Background()
authJson, err := ioutil.ReadFile(clientCredentialsJson)
if err != nil {
fmt.Println("error opening google credentials json,", err)
} else {
config, err := google.JWTConfigFromJSON(authJson, drive.DriveReadonlyScope)
if err != nil {
fmt.Println("error parsing google credentials json,", err)
} else {
client := config.Client(ctx)
DriveService, err = drive.New(client)
if err != nil {
fmt.Println("error setting up google drive client,", err)
}
}
}
}
err = dg.Open()
if err != nil {
fmt.Println("error opening connection,", err)
return
}
u, err := dg.User("@me")
if err != nil {
fmt.Println("error obtaining account details,", err)
}
fmt.Printf("Client is now connected as %s. Press CTRL-C to exit.\n",
u.Username)
DiscordUserId = u.ID
updateDiscordStatus()
// keep program running until CTRL-C is pressed.
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
<-sc
myDB.Close()
return
}
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
handleDiscordMessage(m.Message)
}
func messageUpdate(s *discordgo.Session, m *discordgo.MessageUpdate) {
if m.EditedTimestamp != discordgo.Timestamp("") {
handleDiscordMessage(m.Message)
}
}
func getDownloadLinks(inputURL string, channelID string, interactive bool) map[string]string {
if RegexpUrlTwitter.MatchString(inputURL) {
links, err := getTwitterUrls(inputURL)
if err != nil {
fmt.Println("twitter URL failed,", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlTwitterStatus.MatchString(inputURL) {
links, err := getTwitterStatusUrls(inputURL, channelID)
if err != nil {
fmt.Println("twitter status URL failed,", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlTistory.MatchString(inputURL) {
links, err := getTistoryUrls(inputURL)
if err != nil {
fmt.Println("tistory URL failed,", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlGfycat.MatchString(inputURL) {
links, err := getGfycatUrls(inputURL)
if err != nil {
fmt.Println("gfycat URL failed,", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlInstagram.MatchString(inputURL) {
links, err := getInstagramUrls(inputURL)
if err != nil {
fmt.Println("instagram URL failed,", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlImgurSingle.MatchString(inputURL) {
links, err := getImgurSingleUrls(inputURL)
if err != nil {
fmt.Println("imgur single URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlImgurAlbum.MatchString(inputURL) {
links, err := getImgurAlbumUrls(inputURL)
if err != nil {
fmt.Println("imgur album URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlGoogleDrive.MatchString(inputURL) {
links, err := getGoogleDriveUrls(inputURL)
if err != nil {
fmt.Println("google drive album URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlFlickrPhoto.MatchString(inputURL) {
links, err := getFlickrPhotoUrls(inputURL)
if err != nil {
fmt.Println("flickr photo URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlFlickrAlbum.MatchString(inputURL) {
links, err := getFlickrAlbumUrls(inputURL)
if err != nil {
fmt.Println("flickr album URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlFlickrAlbumShort.MatchString(inputURL) {
links, err := getFlickrAlbumShortUrls(inputURL)
if err != nil {
fmt.Println("flickr album short URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if RegexpUrlStreamable.MatchString(inputURL) {
links, err := getStreamableUrls(inputURL)
if err != nil {
fmt.Println("streamable URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
if DownloadTistorySites {
if RegexpUrlPossibleTistorySite.MatchString(inputURL) {
links, err := getPossibleTistorySiteUrls(inputURL)
if err != nil {
fmt.Println("checking for tistory site failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
}
}
if RegexpUrlGoogleDriveFolder.MatchString(inputURL) {
if interactive {
links, err := getGoogleDriveFolderUrls(inputURL)
if err != nil {
fmt.Println("google drive folder URL failed, ", inputURL, ",", err)
} else if len(links) > 0 {
return skipDuplicateLinks(links, channelID, interactive)
}
} else {
fmt.Println("google drive folder only accepted in interactive channels")
}
}
// try without queries
parsedURL, err := url.Parse(inputURL)
if err == nil {
parsedURL.RawQuery = ""
inputURLWithoutQueries := parsedURL.String()
if inputURLWithoutQueries != inputURL {
return getDownloadLinks(inputURLWithoutQueries, channelID, interactive)
}
}
return map[string]string{inputURL: ""}
}
func skipDuplicateLinks(linkList map[string]string, channelID string, interactive bool) map[string]string {
if interactive == false {
newList := make(map[string]string, 0)
for link, filename := range linkList {
downloadedImages := findDownloadedImageByUrl(link)
isMatched := false
for _, downloadedImage := range downloadedImages {
if downloadedImage.ChannelId == channelID {
isMatched = true
}
}
if isMatched == false {
newList[link] = filename
} else {
fmt.Println("url already downloaded in this channel:", link)
}
}
return newList
}
return linkList
}
func handleDiscordMessage(m *discordgo.Message) {
if folderName, ok := ChannelWhitelist[m.ChannelID]; ok {
fileTime := time.Now()
var err error
if m.Timestamp != "" {
fileTime, err = m.Timestamp.Parse()
if err != nil {
fmt.Println(err)
}
}
if m.Author == nil {
m.Author = new(discordgo.User)
}
for _, iAttachment := range m.Attachments {
startDownload(iAttachment.URL, iAttachment.Filename, folderName, m.ChannelID, m.Author.ID, fileTime)
}
foundUrls := xurls.Strict().FindAllString(m.Content, -1)
for _, iFoundUrl := range foundUrls {
links := getDownloadLinks(iFoundUrl, m.ChannelID, false)
for link, filename := range links {
startDownload(link, filename, folderName, m.ChannelID, m.Author.ID, fileTime)
}
}
if m.Embeds != nil && len(m.Embeds) > 0 {
for _, embed := range m.Embeds {
if embed.Provider != nil {
// skip preview official embeds to prevent duplictes
continue
}
if embed.URL != "" {
links := getDownloadLinks(embed.URL, m.ChannelID, false)
for link, filename := range links {
startDownload(link, filename, folderName, m.ChannelID, m.Author.ID, fileTime)
}
}
if embed.Description != "" {
foundUrls := xurls.Strict().FindAllString(embed.Description, -1)
for _, iFoundUrl := range foundUrls {
links := getDownloadLinks(iFoundUrl, m.ChannelID, false)
for link, filename := range links {
startDownload(link, filename, folderName, m.ChannelID, m.Author.ID, fileTime)
}
}
}
if embed.Image != nil && embed.Image.URL != "" {
links := getDownloadLinks(embed.Image.URL, m.ChannelID, false)
for link, filename := range links {
startDownload(link, filename, folderName, m.ChannelID, m.Author.ID, fileTime)
}
}
if embed.Video != nil && embed.Video.URL != "" {
links := getDownloadLinks(embed.Video.URL, m.ChannelID, false)
for link, filename := range links {
startDownload(link, filename, folderName, m.ChannelID, m.Author.ID, fileTime)
}
}
}
}
} else if folderName, ok := InteractiveChannelWhitelist[m.ChannelID]; ok {
if DiscordUserId != "" && m.Author != nil && m.Author.ID != DiscordUserId {
dg.ChannelTyping(m.ChannelID)
message := strings.ToLower(m.Content)
_, historyCommandIsActive := historyCommandActive[m.ChannelID]
switch {
case message == "help":
dg.ChannelMessageSend(m.ChannelID,
"**<link>** to download a link\n**version** to find out the version\n**stats** to view stats\n**channels** to list active channels\n**history** to download a full channel history\n**help** to open this help\n ")
case message == "version":
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("discord-image-downloder-go **v%s**", VERSION))
dg.ChannelTyping(m.ChannelID)
if isLatestRelease() {
dg.ChannelMessageSend(m.ChannelID, "version is up to date")
} else {
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("**update available on <%s>**", RELEASE_URL))
}
case message == "channels":
replyMessage := "**channels**\n"
for channelId, channelFolder := range ChannelWhitelist {
channel, err := dg.Channel(channelId)
if err == nil {
if channel.Type == discordgo.ChannelTypeDM {
channelRecipientUsername := "N/A"
for _, recipient := range channel.Recipients {
channelRecipientUsername = recipient.Username
}
replyMessage += fmt.Sprintf("@%s (`#%s`): `%s`\n", channelRecipientUsername, channelId, channelFolder)
} else {
guild, err := dg.Guild(channel.GuildID)
if err == nil {
replyMessage += fmt.Sprintf("#%s/%s (`#%s`): `%s`\n", guild.Name, channel.Name, channelId, channelFolder)
}
}
}
}
replyMessage += "**interactive channels**\n"
for channelId, channelFolder := range InteractiveChannelWhitelist {
channel, err := dg.Channel(channelId)
if err == nil {
if channel.Type == discordgo.ChannelTypeDM {
channelRecipientUsername := "N/A"
for _, recipient := range channel.Recipients {
channelRecipientUsername = recipient.Username
}
replyMessage += fmt.Sprintf("@%s (`#%s`): `%s`\n", channelRecipientUsername, channelId, channelFolder)
} else {
guild, err := dg.Guild(channel.GuildID)
if err == nil {
replyMessage += fmt.Sprintf("#%s/%s (`#%s`): `%s`\n", guild.Name, channel.Name, channelId, channelFolder)
}
}
}
}
for _, page := range Pagify(replyMessage, "\n") {
dg.ChannelMessageSend(m.ChannelID, page)
}
case message == "stats":
dg.ChannelTyping(m.ChannelID)
channelStats := make(map[string]int)
userStats := make(map[string]int)
userGuilds := make(map[string]string)
i := 0
myDB.Use("Downloads").ForEachDoc(func(id int, docContent []byte) (willMoveOn bool) {
downloadedImage := findDownloadedImageById(id)
channelStats[downloadedImage.ChannelId] += 1
userStats[downloadedImage.UserId] += 1
if _, ok := userGuilds[downloadedImage.UserId]; !ok {
channel, err := dg.State.Channel(downloadedImage.ChannelId)
if err == nil && channel.GuildID != "" {
userGuilds[downloadedImage.UserId] = channel.GuildID
}
}
i++
return true
})
channelStatsSorted := sortStringIntMapByValue(channelStats)
userStatsSorted := sortStringIntMapByValue(userStats)
replyMessage := fmt.Sprintf("I downloaded **%d** pictures in **%d** channels by **%d** users\n", i, len(channelStats), len(userStats))
replyMessage += "**channel breakdown**\n"
for _, downloads := range channelStatsSorted {
channel, err := dg.State.Channel(downloads.Key)
if err == nil {
if channel.Type == discordgo.ChannelTypeDM {
channelRecipientUsername := "N/A"
for _, recipient := range channel.Recipients {
channelRecipientUsername = recipient.Username
}
replyMessage += fmt.Sprintf("@%s (`#%s`): **%d** downloads\n", channelRecipientUsername, downloads.Key, downloads.Value)
} else {
guild, err := dg.State.Guild(channel.GuildID)
if err == nil {
replyMessage += fmt.Sprintf("#%s/%s (`#%s`): **%d** downloads\n", guild.Name, channel.Name, downloads.Key, downloads.Value)
} else {
fmt.Println(err)
}
}
} else {
fmt.Println(err)
}
}
replyMessage += "**user breakdown**\n"
userI := 0
for _, downloads := range userStatsSorted {
userI++
if userI > 10 {
replyMessage += "_only the top 10 users get shown_\n"
break
}
if guildId, ok := userGuilds[downloads.Key]; ok {
user, err := dg.State.Member(guildId, downloads.Key)
if err == nil {
replyMessage += fmt.Sprintf("@%s: **%d** downloads\n", user.User.Username, downloads.Value)
} else {
replyMessage += fmt.Sprintf("@`%s`: **%d** downloads\n", downloads.Key, downloads.Value)
}
} else {
replyMessage += fmt.Sprintf("@`%s`: **%d** downloads\n", downloads.Key, downloads.Value)
}
}
for _, page := range Pagify(replyMessage, "\n") {
dg.ChannelMessageSend(m.ChannelID, page)
}
case message == "history", historyCommandIsActive:
i := 0
_, historyCommandIsSet := historyCommandActive[m.ChannelID]
if !historyCommandIsSet || historyCommandActive[m.ChannelID] == "" {
historyCommandActive[m.ChannelID] = ""
idArray := strings.Split(message, ",")
for _, channelValue := range idArray {
channelValue = strings.TrimSpace(channelValue)
if folder, ok := ChannelWhitelist[channelValue]; ok {
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("downloading to `%s`", folder))
historyCommandActive[m.ChannelID] = "downloading"
lastBefore := ""
var lastBeforeTime time.Time
MessageRequestingLoop:
for true {
if SendStatusMessages {
if lastBeforeTime != (time.Time{}) {
fmt.Printf("[%s] Requesting 100 more messages, (before %s)\n", time.Now().Format(time.Stamp), lastBeforeTime)
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Requesting 100 more messages, (before %s)\n", lastBeforeTime))
}
}
messages, err := dg.ChannelMessages(channelValue, 100, lastBefore, "", "")
if err == nil {
if len(messages) <= 0 {
delete(historyCommandActive, m.ChannelID)
break MessageRequestingLoop
}
lastBefore = messages[len(messages)-1].ID
lastBeforeTime, err = messages[len(messages)-1].Timestamp.Parse()
if err != nil {
fmt.Println(err)
}
for _, message := range messages {
fileTime := time.Now()
if m.Timestamp != "" {
fileTime, err = message.Timestamp.Parse()
if err != nil {
fmt.Println(err)
}
}
if historyCommandActive[m.ChannelID] == "cancel" {
delete(historyCommandActive, m.ChannelID)
break MessageRequestingLoop
}
for _, iAttachment := range message.Attachments {
if len(findDownloadedImageByUrl(iAttachment.URL)) == 0 {
i++
startDownload(iAttachment.URL, iAttachment.Filename, folder, message.ChannelID, message.Author.ID, fileTime)
}
}
}
} else {
dg.ChannelMessageSend(m.ChannelID, err.Error())
fmt.Println(err)
delete(historyCommandActive, m.ChannelID)
break MessageRequestingLoop
}
}
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("done, %d download links started!", i))
} else {
dg.ChannelMessageSend(m.ChannelID, "Please tell me one or multiple Channel IDs (separated by commas)\nPlease make sure the channels have been whitelisted before submitting.")
}
}
} else if historyCommandActive[m.ChannelID] == "downloading" && message == "cancel" {
historyCommandActive[m.ChannelID] = "cancel"
}
default:
if link, ok := interactiveChannelLinkTemp[m.ChannelID]; ok {
fileTime := time.Now()
var err error
if m.Timestamp != "" {
fileTime, err = m.Timestamp.Parse()
if err != nil {
fmt.Println(err)
}
}
if m.Content == "." {
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Download of <%s> started", link))
dg.ChannelTyping(m.ChannelID)
delete(interactiveChannelLinkTemp, m.ChannelID)
links := getDownloadLinks(link, m.ChannelID, true)
for linkR, filename := range links {
startDownload(linkR, filename, folderName, m.ChannelID, m.Author.ID, fileTime)
}
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Download of <%s> finished", link))
} else if strings.ToLower(m.Content) == "cancel" {
delete(interactiveChannelLinkTemp, m.ChannelID)
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Download of <%s> cancelled", link))
} else if IsValid(m.Content) {
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Download of <%s> started", link))
dg.ChannelTyping(m.ChannelID)
delete(interactiveChannelLinkTemp, m.ChannelID)
links := getDownloadLinks(link, m.ChannelID, true)
for linkR, filename := range links {
startDownload(linkR, filename, m.Content, m.ChannelID, m.Author.ID, fileTime)
}
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Download of <%s> finished", link))
} else {
dg.ChannelMessageSend(m.ChannelID, "invalid path")
}
} else {
_ = folderName
foundLinks := false
for _, iAttachment := range m.Attachments {
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Where do you want to save <%s>?\nType **.** for default path or **cancel** to cancel the download %s", iAttachment.URL, folderName))
interactiveChannelLinkTemp[m.ChannelID] = iAttachment.URL
foundLinks = true
}
foundUrls := xurls.Strict().FindAllString(m.Content, -1)
for _, iFoundUrl := range foundUrls {
dg.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Where do you want to save <%s>?\nType **.** for default path or **cancel** to cancel the download %s", iFoundUrl, folderName))
interactiveChannelLinkTemp[m.ChannelID] = iFoundUrl
foundLinks = true
}
if foundLinks == false {
dg.ChannelMessageSend(m.ChannelID, "unable to find valid link")
}
}
}
}
}
}
type GithubReleaseApiObject struct {
TagName string `json:"tag_name"`
}
func isLatestRelease() bool {
githubReleaseApiObject := new(GithubReleaseApiObject)
getJson(RELEASE_API_URL, githubReleaseApiObject)
currentVer, err := version.NewVersion(VERSION)
if err != nil {
fmt.Println(err)
return true
}
lastVer, err := version.NewVersion(githubReleaseApiObject.TagName)
if err != nil {
fmt.Println(err)
return true
}
if lastVer.GreaterThan(currentVer) {
return false
}
return true
}
// http://stackoverflow.com/a/35240286/1443726
func IsValid(fp string) bool {
// Check if file already exists
if _, err := os.Stat(fp); err == nil {
return true
}
// Attempt to create it
var d []byte
if err := ioutil.WriteFile(fp, d, 0644); err == nil {
os.Remove(fp) // And delete it
return true
}
return false
}
func getTwitterUrls(url string) (map[string]string, error) {
parts := strings.Split(url, ":")
if len(parts) < 2 {
return nil, errors.New("unable to parse twitter url")
}
return map[string]string{"https:" + parts[1] + ":orig": filenameFromUrl(parts[1])}, nil
}
func getTwitterStatusUrls(url string, channelID string) (map[string]string, error) {
if (twitterConsumerKey == "" || twitterConsumerKey == "your consumer key") ||
(twitterConsumerSecret == "" || twitterConsumerSecret == "your consumer secret") ||
(twitterAccessToken == "" || twitterAccessToken == "your access token") ||
(twitterAccessTokenSecret == "" || twitterAccessTokenSecret == "your access token secret") {
return nil, errors.New("invalid twitter api keys set")
}
twitterConfig := oauth1.NewConfig(twitterConsumerKey, twitterConsumerSecret)
twitterToken := oauth1.NewToken(twitterAccessToken, twitterAccessTokenSecret)
twitterHttpClient := twitterConfig.Client(oauth1.NoContext, twitterToken)
twitterClient := twitter.NewClient(twitterHttpClient)
matches := RegexpUrlTwitterStatus.FindStringSubmatch(url)
statusId, err := strconv.ParseInt(matches[4], 10, 64)
if err != nil {
return nil, err
}
tweet, _, err := twitterClient.Statuses.Show(statusId, nil)
if err != nil {
return nil, err
}
links := make(map[string]string)
if tweet.ExtendedEntities != nil {
for _, tweetMedia := range tweet.ExtendedEntities.Media {
if len(tweetMedia.VideoInfo.Variants) > 0 {
var lastVideoVariant twitter.VideoVariant
for _, videoVariant := range tweetMedia.VideoInfo.Variants {
if videoVariant.Bitrate >= lastVideoVariant.Bitrate {
lastVideoVariant = videoVariant
}
}
if lastVideoVariant.URL != "" {
links[lastVideoVariant.URL] = ""
}
} else {
foundUrls := getDownloadLinks(tweetMedia.MediaURLHttps, channelID, false)
for foundUrlKey, foundUrlValue := range foundUrls {
links[foundUrlKey] = foundUrlValue
}
}
}
}
if tweet.Entities != nil {
for _, tweetUrl := range tweet.Entities.Urls {
foundUrls := getDownloadLinks(tweetUrl.ExpandedURL, channelID, false)
for foundUrlKey, foundUrlValue := range foundUrls {
links[foundUrlKey] = foundUrlValue
}
}
}
return links, nil
}
func getTistoryUrls(url string) (map[string]string, error) {
url = strings.Replace(url, "/image/", "/original/", -1)
return map[string]string{url: ""}, nil
}
func getTistoryWithCDNUrls(urlI string) (map[string]string, error) {
parameters, _ := url.ParseQuery(urlI)
if val, ok := parameters["fname"]; ok {
if len(val) > 0 {
if RegexpUrlTistory.MatchString(val[0]) {
return getTistoryUrls(val[0])
}
}
}
return nil, nil
}
func getGfycatUrls(url string) (map[string]string, error) {
parts := strings.Split(url, "/")
if len(parts) < 3 {
return nil, errors.New("unable to parse gfycat url")
} else {
gfycatId := parts[len(parts)-1]
gfycatObject := new(GfycatObject)
getJson("https://gfycat.com/cajax/get/"+gfycatId, gfycatObject)
gfycatUrl := gfycatObject.GfyItem["mp4Url"]
if url == "" {
return nil, errors.New("failed to read response from gfycat")
}
return map[string]string{gfycatUrl: ""}, nil
}
}
func getInstagramUrls(url string) (map[string]string, error) {
username, shortcode := getInstagramInfo(url)
filename := fmt.Sprintf("instagram %s - %s", username, shortcode)
// if instagram video
videoUrl := getInstagramVideoUrl(url)
if videoUrl != "" {
return map[string]string{videoUrl: filename + filepath.Ext(videoUrl)}, nil
}
// if instagram album
albumUrls := getInstagramAlbumUrls(url)
if len(albumUrls) > 0 {
//fmt.Println("is instagram album")
links := make(map[string]string)
for i, albumUrl := range albumUrls {
links[albumUrl] = filename + " " + strconv.Itoa(i+1) + filepath.Ext(albumUrl)
}
return links, nil
}
// if instagram picture
afterLastSlash := strings.LastIndex(url, "/")
mediaUrl := url[:afterLastSlash]
mediaUrl += strings.Replace(strings.Replace(url[afterLastSlash:], "?", "&", -1), "/", "/media/?size=l", -1)
return map[string]string{mediaUrl: filename + ".jpg"}, nil
}
func getInstagramInfo(url string) (string, string) {
resp, err := http.Get(url)
if err != nil {
return "N/A", "N/A"
}
defer resp.Body.Close()
z := html.NewTokenizer(resp.Body)
ParseLoop:
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
break ParseLoop
}
if tt == html.StartTagToken || tt == html.SelfClosingTagToken {
t := z.Token()
for _, a := range t.Attr {
if a.Key == "type" {
if a.Val == "text/javascript" {
z.Next()
content := string(z.Text())
if strings.Contains(content, "window._sharedData = ") {
content = strings.Replace(content, "window._sharedData = ", "", 1)
content = content[:len(content)-1]
jsonParsed, err := gabs.ParseJSON([]byte(content))
if err != nil {
fmt.Println("error parsing instagram json: ", err)
continue ParseLoop
}
entryChildren, err := jsonParsed.Path("entry_data.PostPage").Children()
if err != nil {
fmt.Println("unable to find entries children: ", err)
continue ParseLoop
}
for _, entryChild := range entryChildren {
shortcode := entryChild.Path("graphql.shortcode_media.shortcode").Data().(string)