-
Notifications
You must be signed in to change notification settings - Fork 2
/
ghost.go
1859 lines (1628 loc) · 46.5 KB
/
ghost.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 ghost provides methods for interacting with the Snapchat API.
package ghost
import (
"bytes"
"compress/gzip"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/tls"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math/big"
"mime/multipart"
"net/http"
"net/textproto"
"net/url"
"os"
"strconv"
"strings"
"time"
phone "github.com/dicefm/extra-terrestrial/phone"
"github.com/hako/casper"
)
// Snapchat general constants.
const (
SnapchatVersion = "9.19.0.0"
URL = "https://app.snapchat.com"
UserAgent = "Snapchat/" + SnapchatVersion + " (HTC One; Android 5.0.2#482424.2#21; gzip)"
AcceptLang = "en"
AcceptLocale = "en_US"
Pattern = "0001110111101110001111010101111011010001001110011000110001000110"
Secret = "iEk21fuwZApXlz93750dmW22pw389dPwOk"
StaticToken = "m198sOkJEn37DjqZ32lpRu76xmw288xSQ9"
BlobEncryptionKey = "M02cnQ51Ji97vwT4"
JPEGSignature = "FFD8FFE0"
MP4Signature = "000000186674797033677035"
ZipSignature = "504B0304"
)
// Snapchat media constants.
const (
MediaImage SnapchatMediaType = iota
MediaVideo
MediaVideoNoAudio
MediaFriendRequest
MediaFriendRequestImage
MediaFriendRequestVideo
MediaFriendRequestNoAudio
)
// Snapchat Snap statuses.
const (
StatusNone SnapchatStatus = iota - 1
StatusSent
StatusDelivered
StatusOpened
StatusScreenShot
)
// Snapchat Friend statuses.
const (
FriendConfirmed SnapchatFriendStatus = iota
FriendUnconfirmed
FriendBlocked
FriendDeleted
FriendFollowing = 6
)
// Snapchat Privacy settings
const (
PrivacyEveryone SnapchatPrivacySetting = iota
PrivacyFriends
)
// Supported Snaptag formats.
const (
SnapTagPNG SnapTagImageFormat = "PNG"
SnapTagSVG SnapTagImageFormat = "SVG"
)
// SnapchatMediaType represents the a Snapchat media type.
type SnapchatMediaType int
// SnapchatStatus represents a Snapchat status type.
type SnapchatStatus int
// SnapchatFriendStatus represents a Snapchat friend status type.
type SnapchatFriendStatus int
// SnapchatPrivacySetting represents a Snapchat privacy setting.
type SnapchatPrivacySetting int
// SnapTagImageFormat represents a downloadable Snaptag image format.
type SnapTagImageFormat string
// Account represents a single Snapchat account.
type Account struct {
GoogleMail string
GooglePassword string
CasperClient *casper.Casper
Debug bool
AndroidAuthToken string
Token string
Username string
Password string
UserID string
ProxyURL *url.URL
}
// Error handles errors returned by ghost methods.
type Error struct {
Err SnapchatError
}
func (e Error) Error() string {
return fmt.Sprintf("Error: Snapchat said: %s, Status code: %d, Logged In: %t", e.Err.Message, e.Err.Status, e.Err.Logged)
}
// NewAccount creates a new Snapchat Account of type *Account.
func NewAccount(gmail, gpassword string, cc *casper.Casper, debug bool) *Account {
ghostAcc := &Account{
GoogleMail: gmail,
GooglePassword: gpassword,
CasperClient: cc,
Debug: debug,
AndroidAuthToken: "",
}
return ghostAcc
}
// NewGhostCasperClient creates a new Casper API client of type *casper.Casper.
func NewGhostCasperClient(apiKey, apiSecret, username, password string, debug bool) *casper.Casper {
casperClient := &casper.Casper{
APIKey: apiKey,
APISecret: apiSecret,
Username: username,
Password: password,
Debug: debug,
}
return casperClient
}
// NewRawCasperClient creates an empty Casper API client of type *casper.Casper.
// Same as NewGhostCasperClient() But configurable.
func NewRawCasperClient(apiKey, apiSecret string) *casper.Casper {
casperClient := &casper.Casper{
APIKey: apiKey,
APISecret: apiSecret,
}
return casperClient
}
// NewRawAccount creates an empty Snapchat Account client of type *Account.
// Same as NewAccount() But configurable.
func NewRawAccount() *Account {
return &Account{}
}
// DecodeSnaptag decodes Snapchat 'Snaptags'.
func DecodeSnaptag(snaptag string) {
b, _ := hex.DecodeString(snaptag)
for _, v := range b {
fmt.Println(strconv.FormatInt(int64(v), 2))
}
}
// AddPKCS5 pads plaintext with PKCS5.
func AddPKCS5(plaintext []byte) []byte {
padding := aes.BlockSize - (len(plaintext) % aes.BlockSize)
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(plaintext, padtext...)
}
// RemovePKCS5 removes padding from plaintext.
func RemovePKCS5(plaintext []byte) []byte {
unpadding := int(plaintext[len(plaintext)-1])
return plaintext[:(len(plaintext) - unpadding)]
}
// DecryptECB decrypts data using ECB.
func DecryptECB(key, data []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
if len(data) < aes.BlockSize {
fmt.Println("Ciphertext is too short")
}
if len(data)%aes.BlockSize != 0 {
fmt.Println("Ciphertext is not a multiple of the block size")
}
j := len(data) / aes.BlockSize
var decrypted []byte
for i := 0; i < j; i++ {
low := i * aes.BlockSize
high := low + aes.BlockSize
out := make([]byte, aes.BlockSize)
block.Decrypt(out, data[low:high])
tmp := [][]byte{decrypted, out}
decrypted = bytes.Join(tmp, nil)
}
return decrypted
}
// EncryptECB encrypts data using ECB.
func EncryptECB(key, data []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
if len(data)%aes.BlockSize != 0 {
fmt.Println("Plaintext is not a multiple of the block size")
}
j := len(data) / aes.BlockSize
var encrypted []byte
for i := 0; i < j; i++ {
low := i * aes.BlockSize
high := low + aes.BlockSize
out := make([]byte, aes.BlockSize)
block.Encrypt(out, data[low:high])
tmp := [][]byte{encrypted, out}
encrypted = bytes.Join(tmp, nil)
}
return encrypted
}
// DecryptCBC decrypts data using CBC.
func DecryptCBC(data []byte, b64Iv, b64Key string) []byte {
key, err := base64.StdEncoding.DecodeString(b64Key)
if err != nil {
fmt.Println(err)
}
iv, err := base64.StdEncoding.DecodeString(b64Iv)
if err != nil {
fmt.Println(err)
}
block, err := aes.NewCipher(key)
if err != nil {
fmt.Println(err)
}
if len(data) < aes.BlockSize {
fmt.Println("Ciphertext is too short")
}
if len(data)%aes.BlockSize != 0 {
fmt.Println("Ciphertext is not a multiple of the block size")
}
decryptor := cipher.NewCBCDecrypter(block, iv)
decryptor.CryptBlocks(data, data)
return data
}
// IsJPEG checks if data is a JPEG image.
func IsJPEG(data []byte) bool {
sig, err := hex.DecodeString(JPEGSignature)
if err != nil {
return false
}
if bytes.Equal(data[:len(sig)], sig) {
return true
}
return false
}
// IsMP4 checks if data is a MP4 video.
func IsMP4(data []byte) bool {
sig, err := hex.DecodeString(MP4Signature)
if err != nil {
return false
}
if bytes.Equal(data[:len(sig)], sig) {
return true
}
return false
}
// IsZIP checks if data is a ZIP file.
func IsZIP(data []byte) bool {
sig, err := hex.DecodeString(ZipSignature)
if err != nil {
return false
}
if bytes.Equal(data[:len(sig)], sig) {
return true
}
return false
}
// CalculateAge calculates the age of a Snapchat user.
func CalculateAge(date string) (string, error) {
now := time.Now()
birthday, err := time.Parse("2006-01-02", date)
if err != nil {
return "", err
}
return strconv.Itoa(now.Year() - birthday.Year()), nil
}
// structToJSON is a helper method for converting Snapchat structs To JSON.
func structToJSON(jsn interface{}) string {
bytes, err := json.Marshal(jsn)
if err != nil {
fmt.Println(err)
}
return string(bytes)
}
// AddJPEGSignature appends a JPEG magic number to data.
func AddJPEGSignature(data []byte) []byte {
sig, err := hex.DecodeString(JPEGSignature)
if err != nil {
fmt.Println(err)
}
return append(sig, data...)
}
// AddMP4Signature appends a MP4 magic number to data.
func AddMP4Signature(data []byte) []byte {
sig, err := hex.DecodeString(MP4Signature)
if err != nil {
fmt.Println(err)
}
return append(sig, data...)
}
// Timestamp generates timestamps in miliseconds.
func Timestamp() string {
return strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 10)
}
// UUID4 Generates (RFC 4122) compatible UUIDs.
func UUID4() string {
b := make([]byte, 16)
_, err := rand.Read(b)
if err != nil {
fmt.Println(err)
}
return fmt.Sprintf("%04x-%02x-%02x-%02x-%06x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}
// MediaID creates Snapchat Media UUIDs using username.
func MediaID(username string) string {
return fmt.Sprintf("%s~%s", strings.ToUpper(username), UUID4())
}
// EncryptSnap is a small wrapper around AddPKCS5 & EncryptECB.
func EncryptSnap(file []byte) ([]byte, error) {
if len(file) == 0 {
return nil, errors.New("File does not exist.")
}
padFile := AddPKCS5(file)
encryptedFile := EncryptECB([]byte(BlobEncryptionKey), padFile)
return encryptedFile, nil
}
// DetectMedia is a small wrapper around IsJPEG & IsMP4.
func DetectMedia(file []byte) (string, error) {
var mt SnapchatMediaType
if len(file) == 0 {
return "", errors.New("File does not exist.")
}
if IsJPEG(file) == true {
mt = MediaImage
} else if IsMP4(file) == true || IsZIP(file) == true {
mt = MediaVideo
} else {
return "", errors.New("Unknown file type.")
}
return strconv.Itoa(int(mt)), nil
}
// RequestToken generates request tokens on each Snapchat API request.
func RequestToken(AuthToken, timestamp string) string {
hash := sha256.New()
io.WriteString(hash, Secret+AuthToken)
first := hex.EncodeToString(hash.Sum(nil))
hash.Reset()
io.WriteString(hash, timestamp+Secret)
second := hex.EncodeToString(hash.Sum(nil))
var bits string
for i, c := range Pattern {
if c == '0' {
bits += string(first[i])
} else {
bits += string(second[i])
}
}
return bits
}
// encryptPasswd is an implemention of Google's EncryptPasswd for encrypting Google account passwords.
func (acc *Account) encryptPasswd() string {
googleDefaultPubKey := "AAAAgMom/1a/v0lblO2Ubrt60J2gcuXSljGFQXgcyZWveWLEwo6prwgi3iJIZdodyhKZQrNWp5nKJ3srRXcUW+F1BD3baEVGcmEgqaLZUNBjm057pKRI16kB0YppeGx5qIQ5QjKzsR8ETQbKLNWgRY0QRNVz34kMJR3P/LgHax/6rmf5AAAAAwEAAQ=="
b64DecodedKey, err := base64.StdEncoding.DecodeString(googleDefaultPubKey)
if err != nil {
fmt.Println(err)
}
bigintMod := new(big.Int)
bigintExp := new(big.Int)
binarykey := hex.EncodeToString([]byte(b64DecodedKey))
half := binarykey[8:264]
modulus, b := bigintMod.SetString(half, 16)
if b != true {
fmt.Println(modulus, b)
}
half = binarykey[272:]
bigExponent, b := bigintExp.SetString(half, 16)
if b != true {
fmt.Println(bigExponent, b)
}
exponent, err := strconv.Atoi(bigExponent.String())
if err != nil {
fmt.Println(err)
}
h := sha1.New()
io.WriteString(h, string(b64DecodedKey))
hash := h.Sum(nil)
signature := "00" + hex.EncodeToString(hash[0:4])
pubkey := &rsa.PublicKey{N: modulus, E: exponent}
plain := acc.GoogleMail + "\x00" + acc.GooglePassword
s := sha1.New()
msg := []byte(plain)
encrypted, err := rsa.EncryptOAEP(s, rand.Reader, pubkey, msg, []byte(""))
if err != nil {
fmt.Println(err)
}
hexencrypted := hex.EncodeToString(encrypted)
output, err := hex.DecodeString(signature + string(hexencrypted))
if err != nil {
fmt.Println(err)
}
pass1 := strings.Replace(base64.StdEncoding.EncodeToString(output), "+", "-", -1)
b64encryptedPasswd := strings.Replace(pass1, "/", "_", -1)
return b64encryptedPasswd
}
// GetGCMToken fetches a GCM token from (You guessed it) Google.
func (acc *Account) GetGCMToken() string {
var tr *http.Transport
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
if acc.ProxyURL != nil {
tr.Proxy = http.ProxyURL(acc.ProxyURL)
}
client := &http.Client{Transport: tr}
clientGCMForm := url.Values{}
clientGCMForm.Add("device", "3847872624728098287")
clientGCMForm.Add("sender", "191410808405")
clientGCMForm.Add("app_ver", "564")
clientGCMForm.Add("gcm_ver", "7097038")
clientGCMForm.Add("app", "com.snapchat.android")
clientGCMForm.Add("iat", Timestamp())
clientGCMForm.Add("cert", "49f6badb81d89a9e38d65de76f09355071bd67e7")
req, err := http.NewRequest("POST", "https://android.clients.google.com/c2dm/register3", strings.NewReader(string(clientGCMForm.Encode())))
req.Header.Set("App", "com.snapchat.android")
req.Header.Set("User-Agent", "Android-GCM/1.5 (m7 KOT49H)")
req.Header.Set("Authorization", "AidLogin 3847872624728098287:1187196130325105010")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept-Encoding", "gzip")
resp, err := client.Do(req)
gzBody, err := gzip.NewReader(resp.Body)
decompressedBody, err := ioutil.ReadAll(gzBody)
if acc.Debug == true {
fmt.Println(string(decompressedBody))
}
if err != nil {
fmt.Println(err)
}
token := string(decompressedBody)[6:]
return token
}
// GetAuthToken fetches an Android auth token.
func (acc *Account) GetAuthToken() string {
var tr *http.Transport
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
if acc.ProxyURL != nil {
tr.Proxy = http.ProxyURL(acc.ProxyURL)
}
encyptedPassword := acc.encryptPasswd()
client := &http.Client{Transport: tr}
authForm := url.Values{}
authForm.Add("device_country", "us")
authForm.Add("operatorCountry", "us")
authForm.Add("lang", "en_US")
authForm.Add("sdk_version", "19")
authForm.Add("google_play_services_version", "7097038")
authForm.Add("accountType", "HOSTED_OR_GOOGLE")
authForm.Add("Email", acc.GoogleMail)
authForm.Add("service", "audience:server:client_id:694893979329-l59f3phl42et9clpoo296d8raqoljl6p.apps.googleusercontent.com")
authForm.Add("source", "android")
authForm.Add("androidId", "378c184c6070c26c")
authForm.Add("app", "com.snapchat.android")
authForm.Add("client_sig", "49f6badb81d89a9e38d65de76f09355071bd67e7")
authForm.Add("callerPkg", "com.snapchat.android")
authForm.Add("callerSig", "49f6badb81d89a9e38d65de76f09355071bd67e7")
authForm.Add("EncryptedPasswd", encyptedPassword)
req, err := http.NewRequest("POST", "https://android.clients.google.com/auth", strings.NewReader(string(authForm.Encode())))
req.Header.Set("User-Agent", "GoogleAuth/1.4 (mako JDQ39)")
req.Header.Set("Device", "378c184c6070c26c")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("App", "com.snapchat.android")
req.Header.Set("Accept", "*/*")
req.Header.Set("Accept-Encoding", "gzip")
resp, err := client.Do(req)
gzBody, err := gzip.NewReader(resp.Body)
decompressedBody, err := ioutil.ReadAll(gzBody)
if err != nil {
fmt.Println(err)
}
if acc.Debug == true {
fmt.Println(string(decompressedBody))
}
splitString := strings.Split(string(decompressedBody), "issueAdvice")
authToken := splitString[0][5:]
return authToken
}
// GetDeviceToken fetches the device token to use with Snapchat.
func (acc *Account) GetDeviceToken() map[string]interface{} {
ts := Timestamp()
acc.SetAuthToken(acc.GetAuthToken())
data := map[string]string{
"timestamp": ts,
"req_token": RequestToken(StaticToken, ts),
}
resp := acc.SendRequest("POST", "/loq/device_id", data)
body, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
fmt.Println(ioErr)
}
if acc.Debug == true {
fmt.Println(string(body))
}
var parsed map[string]interface{}
json.Unmarshal(body, &parsed)
return parsed
}
// SetAuthToken sets the auth token auth to current Snapchat account acc.
func (acc *Account) SetAuthToken(auth string) {
acc.AndroidAuthToken = auth
}
// AuthToken returns the auth token associated with the current Snapchat account acc.
func (acc *Account) AuthToken() string {
return acc.AndroidAuthToken
}
// SendRequest performs HTTP requests.
func (acc *Account) SendRequest(method, endpoint string, data map[string]string) *http.Response {
var tr *http.Transport
var req *http.Request
var form url.Values
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
if acc.ProxyURL != nil {
tr.Proxy = http.ProxyURL(acc.ProxyURL)
}
if acc.Debug == true {
fmt.Printf(method+"\t%s\n", URL+endpoint)
}
if data != nil {
form = url.Values{}
for k, v := range data {
form.Add(k, v)
if acc.Debug == true {
fmt.Printf("%s\t%s\n", k, v)
}
}
}
client := &http.Client{Transport: tr}
if method == "GET" {
req, _ = http.NewRequest(method, URL+endpoint, nil)
} else {
req, _ = http.NewRequest(method, URL+endpoint, strings.NewReader(form.Encode()))
}
req.Header.Set("User-Agent", UserAgent)
if method == "POST" {
if endpoint == "/bq/solve_captcha" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
} else {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
androidAuthToken := acc.AuthToken()
if endpoint == "/loq/login" || endpoint == "/loq/device_id" || endpoint == "/bq/solve_captcha" {
clientAuthToken, err := acc.CasperClient.GetClientAuthToken(acc.Username, acc.Password, data["timestamp"])
if err != nil {
fmt.Println(err)
}
req.Header.Set("X-Snapchat-Client-Auth-Token", "Bearer "+androidAuthToken)
req.Header.Set("X-Snapchat-Client-Auth", clientAuthToken)
} else {
req.Header.Set("X-Snapchat-Client-Auth-Token", "Bearer "+androidAuthToken)
}
}
req.Header.Set("Accept-Language", AcceptLang)
req.Header.Set("Accept-Locale", AcceptLocale)
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
return resp
}
// Performs multipart HTTP requests. (Not fully implemented)
/*func SendMultipartRequest(endpoint string, data map[string]string, path string) *http.Response {
// For debugging purposes only!
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
ms := multipartstreamer.New()
err := ms.WriteFields(data)
if err != nil {
fmt.Println(err)
}
err = ms.WriteFile("data", path)
if err != nil {
fmt.Println(err)
}
req, err := http.NewRequest("POST", URL+endpoint, ms.GetReader())
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("Accept-Language", AcceptLang)
req.Header.Add("Content-Type", ms.ContentType)
req.ContentLength = ms.Len()
var b []byte
ms.GetReader().Read(b)
fmt.Println(b)
if err != nil {
fmt.Println(err)
}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
return resp
}*/
// SendMultipartRequest performs multipart HTTP requests.
func (acc *Account) SendMultipartRequest(endpoint string, data map[string]string, path string) *http.Response {
var tr *http.Transport
tr = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
file, err := os.Open(path)
if err != nil {
fmt.Println(err)
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
err = writer.SetBoundary("Boundary+0xAbCdEfGbOuNdArY")
if err != nil {
fmt.Println(err)
}
mh := make(textproto.MIMEHeader)
mh.Set("Content-Disposition", "form-data; name=\"data\"; filename=\"data\"")
mh.Set("Content-Type", "application/octet-stream")
partWriter, err := writer.CreatePart(mh)
if err != nil {
fmt.Println(err)
}
if err != nil {
fmt.Println(err)
}
_, err = io.Copy(partWriter, file)
if err != nil {
fmt.Println(err)
}
for k, v := range data {
mh = make(textproto.MIMEHeader)
dpos := fmt.Sprintf("form-data; name=\"%s\"", k)
mh.Set("Content-Disposition", dpos)
partWriter, err = writer.CreatePart(mh)
if nil != err {
panic(err)
}
mh.Set("Boundary", writer.Boundary())
io.Copy(partWriter, bytes.NewBufferString(v))
}
err = writer.Close()
if err != nil {
fmt.Println(err)
}
if acc.ProxyURL != nil {
tr.Proxy = http.ProxyURL(acc.ProxyURL)
}
if acc.Debug == true {
fmt.Printf("POST"+"\t%s\n", URL+endpoint)
}
client := &http.Client{Transport: tr}
req, err := http.NewRequest("POST", URL+endpoint, body)
req.Header.Set("Content-Type", "multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY")
androidAuthToken := acc.AuthToken()
req.Header.Set("Accept-Language", AcceptLang)
req.Header.Set("Accept-Locale", AcceptLocale)
req.Header.Set("User-Agent", UserAgent)
req.Header.Set("X-Snapchat-Client-Auth-Token", "Bearer "+androidAuthToken)
if acc.Debug == true {
for k, v := range req.Header {
fmt.Println(k, v)
}
}
resp, err := client.Do(req)
if err != nil {
fmt.Println(err)
}
return resp
}
// Register registers a new Snapchat account.
func (acc *Account) Register(username, password, email, birthday string) map[string]interface{} {
acc.Username = username
acc.Password = password
ts := Timestamp()
deviceToken := acc.GetDeviceToken()
reqToken := RequestToken(StaticToken, ts)
dsigStr := []byte(email + "|" + password + "|" + ts + "|" + reqToken)
h := hmac.New(sha256.New, []byte(deviceToken["dtoken1v"].(string)))
h.Write(dsigStr)
dsig := hex.EncodeToString(h.Sum(nil))[:20]
dtoken1i := deviceToken["dtoken1i"].(string)
acc.SetAuthToken(acc.GetAuthToken())
age, err := CalculateAge(birthday)
attestation, err := acc.CasperClient.GetAttestation(username, password, ts)
if err != nil {
fmt.Println(err)
}
ssjson := StudySettings{
RegisterHideSkipPhone: RegisterHideSkipPhone{
Experimentid: "0",
},
}
studySettings := structToJSON(ssjson)
data := map[string]string{
"timestamp": ts,
"req_token": RequestToken(StaticToken, ts),
"email": email,
"password": password,
"dsig": dsig,
"study_settings": studySettings,
"dtoken1i": dtoken1i,
"attestation": attestation,
"age": age,
"birthday": birthday,
}
resp := acc.SendRequest("POST", "/loq/register", data)
body, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
fmt.Println(ioErr)
}
if acc.Debug == true {
fmt.Println(string(body))
}
var parsed map[string]interface{}
json.Unmarshal(body, &parsed)
return parsed
}
// RegisterUsername registers a new Snapchat username.
func (acc *Account) RegisterUsername(username, email string) map[string]interface{} {
ts := Timestamp()
data := map[string]string{
"timestamp": ts,
"req_token": RequestToken(acc.Token, ts),
"username": email,
"selected_username": username,
}
resp := acc.SendRequest("POST", "/loq/register_username", data)
body, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
fmt.Println(ioErr)
}
if acc.Debug == true {
fmt.Println(string(body))
}
var parsed map[string]interface{}
json.Unmarshal(body, &parsed)
return parsed
}
// VerifyPhoneNumber sends a phone number to Snapchat for verification.
func (acc *Account) VerifyPhoneNumber(phoneNumber string) map[string]interface{} {
ts := Timestamp()
number, err := phone.Normalise(phoneNumber, "")
if err != nil {
fmt.Println(err)
}
// Get country code out of phone number.
data := map[string]string{
"timestamp": ts,
"req_token": RequestToken(acc.Token, ts),
"username": acc.Username,
"countryCode": number.Country[:2],
"skipConfirmation": "true",
"phoneNumber": phoneNumber,
"action": "updatePhoneNumber",
}
resp := acc.SendRequest("POST", "/bq/phone_verify", data)
body, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
fmt.Println(ioErr)
}
if acc.Debug == true {
fmt.Println(string(body))
}
var parsed map[string]interface{}
json.Unmarshal(body, &parsed)
return parsed
}
// SendSMSCode sends an SMS code to Snapchat.
func (acc *Account) SendSMSCode(code string) map[string]interface{} {
ts := Timestamp()
data := map[string]string{
"timestamp": ts,
"req_token": RequestToken(acc.Token, ts),
"username": acc.Username,
"action": "verifyPhoneNumber",
"code": code,
"type": "DEFAULT_TYPE",
}
resp := acc.SendRequest("POST", "/bq/phone_verify", data)
body, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
fmt.Println(ioErr)
}
if acc.Debug == true {
fmt.Println(string(body))
}
var parsed map[string]interface{}
json.Unmarshal(body, &parsed)
return parsed
}
// GetCaptcha fetches a captcha puzzle from snapchat.
func (acc *Account) GetCaptcha() string {
ts := Timestamp()
data := map[string]string{
"timestamp": ts,
"req_token": RequestToken(acc.Token, ts),
"username": acc.Username,
}
resp := acc.SendRequest("POST", "/bq/get_captcha", data)
body, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
fmt.Println(ioErr)
}
filename := resp.Header["Content-Disposition"][0][20:]
if acc.Debug == true {
fmt.Println("< CAPTCHA ZIP: " + filename + " >")
}
captchaID := strings.Replace(filename, ".zip", "", 1)
ioutil.WriteFile(filename, body, 0644)
return captchaID
}
// SolveCaptcha fetches a captcha puzzle from snapchat.
func (acc *Account) SolveCaptcha(captchaID, solution string) map[string]interface{} {
ts := Timestamp()
data := map[string]string{
"timestamp": ts,
"captcha_solution": solution,
"captcha_id": captchaID,
"req_token": RequestToken(acc.Token, ts),
"username": acc.Username,
}
resp := acc.SendRequest("POST", "/bq/solve_captcha", data)
body, ioErr := ioutil.ReadAll(resp.Body)
if ioErr != nil {
fmt.Println(ioErr)
}
if acc.Debug == true {
fmt.Println(string(body))
}
var parsed map[string]interface{}
json.Unmarshal(body, &parsed)
return parsed
}
// RegisterExpire expires a device id.
// (This happens when the user presses cancel when signing up.)
// func (acc *Account) RegisterExpire(device_id string) map[string]interface{} {
// ts := Timestamp()
// data := map[string]string{
// "timestamp": ts,
// "req_token": RequestToken(acc.Token, ts),
// "device_unique_id": device_unique_id,
// }
// resp := acc.SendRequest("POST", "/loq/and/register_exp", data)
// body, ioErr := ioutil.ReadAll(resp.Body)
// fmt.Println(string(body))
// if ioErr != nil {
// fmt.Println(ioErr)
// }