-
Notifications
You must be signed in to change notification settings - Fork 58
/
env.go
513 lines (458 loc) · 12.5 KB
/
env.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
package goinsta
import (
"bytes"
"errors"
"fmt"
"math/rand"
"os"
"strings"
"time"
)
// EnvPlainAcc represents the plain account details stored in the env variable:
//
// INSTAGRAM_ACT_<name>="username:password"
type EnvPlainAcc struct {
Name string
Username string
Password string
}
// EnvEncAcc represents the encoded account details stored in the env variable:
//
// INSTAGRAM_BASE64_<name>="<base64 encoded config>"
type EnvEncAcc struct {
Name string
Username string
Base64 string
}
// EnvAcc represents the pair of plain and base64 encoded account pairs as
// stored in EnvPlainAcc and EnvEncAcc, with env variables:
//
// INSTAGRAM_ACT_<name>="username:password"
// INSTAGRAM_BASE64_<name>="<base64 encoded config>"
type EnvAcc struct {
Plain *EnvPlainAcc
Enc *EnvEncAcc
}
var (
errNoAcc = errors.New("no account found")
)
// EnvRandAcc will check the environment variables, and the .env file in
// the current working directory (unless another path has been provided),
// for either a base64 encoded goinsta config, or plain credentials.
//
// To use this function, add one or multiple of the following:
// INSTAGRAM_ACT_<name>="username:password"
// INSTAGRAM_BASE64_<name>="<base64 encoded config>"
//
// INSTAGRAM_ACT_ variables will automatiaclly be converted to INSTAGRAM_BASE64_
//
func EnvRandAcc(path ...string) (*Instagram, error) {
err := checkEnv(path...)
if err != nil {
return nil, err
}
return getRandAcc(path...)
}
// EnvRandLogin fetches a random login from the env.
// :param: path (OPTIONAL) - path to a file, by default .env
//
// Looks for INSTAGRAM_ACT_<name>="username:password" in env
//
func EnvRandLogin(path ...string) (string, string, error) {
allAccs, err := EnvReadAccs(path...)
if err != nil {
return "", "", err
}
// extract plain accounts from all accounts
accs := []*EnvPlainAcc{}
for _, acc := range allAccs {
if acc.Plain != nil {
accs = append(accs, acc.Plain)
}
}
// find valid one, until list exhausted
for {
i := rand.Intn(len(accs))
r := accs[i]
if r.Username != "" && r.Password != "" {
return r.Username, r.Password, nil
}
accs = append(accs[:i], accs[i+1:]...)
if len(accs) == 0 {
return "", "", ErrNoValidLogin
}
}
}
// EnvProvision will check the environment variables for INSTAGRAM_ACT_ and
// create a base64 encoded config for the account, and write it to path.
//
// :param: path - path a file to use as env, commonly a .env, but not required.
// :param: refresh (OPTIONAL) - refresh all plaintext credentials, don't skip already converted accounts
//
// This function has been created the use of a .env file in mind.
//
// .env contents:
// INSTAGRAM_ACT_<name>="user:pass"
//
// This function will add to the .env:
// INSTAGRAM_BASE64_<name>="..."
//
func EnvProvision(path string, refresh ...bool) error {
// By default, skip exisitng accounts
refreshFlag := len(refresh) == 0 || (len(refresh) > 0 && !refresh[0])
fmt.Printf("Force refresh is set to %v\n", refreshFlag)
accs, _, err := envLoadAccs(path)
if err != nil {
return err
}
fmt.Printf("Found %d accounts\n", len(accs))
for _, acc := range accs {
if acc.Enc != nil && !refreshFlag {
fmt.Printf("Skipping account %s\n", acc.Plain.Name)
continue
}
username := acc.Plain.Username
password := acc.Plain.Password
fmt.Println("Processing", username)
insta := New(username, password)
if err := insta.Login(); err != nil {
return err
}
// Export Config
enc, err := insta.ExportAsBase64String()
if err != nil {
return err
}
acc.Enc.Base64 = enc
fmt.Println("Sleeping...")
time.Sleep(20 * time.Second)
}
err = accsToFile(path, accs)
if err != nil {
return err
}
return nil
}
// EnvUpdateAccs will update the plain and encoded account variables stored in
// the .env file:
//
// INSTAGRAM_ACT_<name>="username:password"
// INSTAGRAM_BASE64_<name>="<base64 encoded config>"
//
// :param: string:path -- file path of the .env file, typically ".env"
// :param: []*EncAcc:newAccs -- list of updated versions of the accounts
func EnvUpdateAccs(path string, newAccs []*EnvAcc) error {
return envUpdateAccs(path, newAccs)
}
// EnvUpdateEnc will update the encoded account variables stored in
// the .env file:
//
// INSTAGRAM_BASE64_<name>="<base64 encoded config>"
//
// :param: string:path -- file path of the .env file, typically ".env"
// :param: []*EnvEncAcc:newAccs -- list of updated encoded accounts
func EnvUpdateEnc(path string, newAccs []*EnvEncAcc) error {
return envUpdateAccs(path, newAccs)
}
// EnvPlainAccs will update the plain account variables stored in
// the .env file:
//
// INSTAGRAM_ACT_<name>="username:password"
//
// :param: string:path -- file path of the .env file, typically ".env"
// :param: []*EnvPlainAcc:newAccs -- list of updated plain accounts
func EnvUpdatePlain(path string, newAccs []*EnvPlainAcc) error {
return envUpdateAccs(path, newAccs)
}
func envUpdateAccs(path string, newAccs interface{}) error {
accs, _, err := dotenv(path)
if err != nil {
return err
}
switch n := newAccs.(type) {
case []*EnvAcc:
case []*EnvPlainAcc:
for _, acc := range n {
accs = addOrUpdateAcc(accs, acc)
}
case []*EnvEncAcc:
for _, acc := range n {
accs = addOrUpdateAcc(accs, acc)
}
}
return accsToFile(path, accs)
}
// checkEnv will check the env variables for accounts that do have a login,
// but no config (INSTAGRAM_BASE64_<...>). If one is found, call ProvisionEnv
func checkEnv(path ...string) error {
accs, err := EnvReadAccs(path...)
if err != nil {
return err
}
// Check for every plain acc, if there is an encoded equivalent
for _, acc := range accs {
if acc.Plain != nil && acc.Enc == nil {
fmt.Println("Unable to find:", acc.Plain.Name, acc.Plain.Username)
p := ".env"
if len(path) > 0 {
p = path[0]
}
if err := EnvProvision(p, true); err != nil {
return err
}
}
}
return nil
}
// getRandAcc returns a random insta instance from env
func getRandAcc(path ...string) (*Instagram, error) {
allAccs, err := EnvReadAccs(path...)
if err != nil {
return nil, err
}
// extract encoded accounts from all accounts
accounts := []*EnvEncAcc{}
for _, acc := range allAccs {
if acc.Enc != nil {
accounts = append(accounts, acc.Enc)
}
}
// validate result
if len(accounts) == 0 {
return nil, ErrNoValidLogin
}
// select rand account
rand.Seed(time.Now().UnixNano())
r := rand.Intn(len(accounts))
// load account config
insta, err := ImportFromBase64String(accounts[r].Base64, true)
if err != nil {
return nil, err
}
// insta.SetProxy("http://localhost:9090", false, true)
return insta, err
}
// EnvLoadPlain will load all plain accounts stored in the env variables:
//
// INSTAGRAM_ACT_<name>="username:password"
//
// :param: path (OPTIONAL) -- .env file to load, default to ".env"
func EnvLoadPlain(path ...string) ([]*EnvPlainAcc, error) {
allAccs, err := EnvReadAccs(path...)
if err != nil {
return nil, err
}
// extract plain accounts from all accounts
accs := []*EnvPlainAcc{}
for _, acc := range allAccs {
if acc.Plain != nil {
accs = append(accs, acc.Plain)
}
}
return accs, nil
}
// EnvLoadAccs loads all the environment variables.
//
// By default, the OS environment variables as well as .env are loaded
// To load a custom file, instead of .env, pass the filepath as an argument.
//
// Don't Sync param is set to true to prevent any http calls on import by default
func EnvLoadAccs(p ...string) ([]*Instagram, error) {
instas := []*Instagram{}
accs, _, err := envLoadAccs(p...)
for _, acc := range accs {
insta, err := ImportFromBase64String(acc.Enc.Base64, true)
if err != nil {
return nil, err
}
instas = append(instas, insta)
}
return instas, err
}
// EnvReadAccs loads both all plain and base64 encoded accounts
//
// Set in a .env file or export to your environment variables:
// INSTAGRAM_ACT_<name>="user:pass"
// INSTAGRAM_BASE64_<name>="..."
//
// :param: p (OPTIONAL) -- env file path, ".env" by default
func EnvReadAccs(p ...string) ([]*EnvAcc, error) {
accs, _, err := envLoadAccs(p...)
return accs, err
}
func envLoadAccs(p ...string) ([]*EnvAcc, []string, error) {
path := ".env"
if len(p) > 0 {
path = p[0]
}
environ := os.Environ()
accsOne, other, err := dotenv(path)
if err != nil {
return nil, nil, err
}
accsTwo, _, err := parseAccs(environ)
if err != nil {
return nil, nil, err
}
accs := append(accsOne, accsTwo...)
if len(accs) == 0 {
return nil, nil, ErrNoValidLogin
}
return accs, other, nil
}
// dotenv loads the file in the path parameter (commonly a .env file) and
// returns its contents.
func dotenv(path string) ([]*EnvAcc, []string, error) {
file, err := os.Open(path)
if err != nil {
return nil, nil, err
}
defer file.Close()
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(file)
if err != nil {
return nil, nil, err
}
lines := strings.Split(buf.String(), "\n")
accs, other, err := parseAccs(lines)
if err != nil {
return nil, nil, err
}
return accs, other, nil
}
func parseAccs(lines []string) ([]*EnvAcc, []string, error) {
accs := []*EnvAcc{}
other := []string{}
for _, line := range lines {
plain, errPlain := parsePlain(line)
if errPlain == nil {
accs = addOrUpdateAcc(accs, plain)
}
enc, errEnc := parseEnc(line)
if errEnc == nil {
accs = addOrUpdateAcc(accs, enc)
} else if errEnc != errNoAcc {
return nil, nil, errEnc
}
// Keep track of other lines in the file, not related to goinsta
if !strings.HasPrefix(line, "INSTAGRAM") {
other = append(other, line)
}
}
return accs, other, nil
}
func parsePlain(line string) (*EnvPlainAcc, error) {
if strings.HasPrefix(line, "INSTAGRAM_ACT_") {
envVar := strings.Split(line, "=")
name := strings.Split(envVar[0], "_")[2]
acc := envVar[1]
if acc[0] == '"' {
acc = acc[1 : len(acc)-1]
}
creds := strings.Split(acc, ":")
return &EnvPlainAcc{
Name: name,
Username: strings.ToLower(creds[0]),
Password: creds[1],
}, nil
}
return nil, errNoAcc
}
func parseEnc(line string) (*EnvEncAcc, error) {
if strings.HasPrefix(line, "INSTAGRAM_BASE64_") {
envVar := strings.SplitN(line, "=", 2)
encodedString := strings.TrimSpace(envVar[1])
name := strings.Split(envVar[0], "_")[2]
if encodedString[0] == '"' {
encodedString = encodedString[1 : len(encodedString)-1]
}
insta, err := ImportFromBase64String(encodedString, true)
if err != nil {
return nil, err
}
return &EnvEncAcc{
Name: name,
Username: insta.Account.Username,
Base64: encodedString,
}, nil
}
return nil, errNoAcc
}
func addOrUpdateAcc(accs []*EnvAcc, toAdd interface{}) []*EnvAcc {
switch newAcc := toAdd.(type) {
case *EnvAcc:
for _, acc := range accs {
if (acc.Enc != nil && newAcc.Plain.Username == acc.Enc.Username) ||
(acc.Plain != nil && newAcc.Enc.Username == acc.Plain.Username) {
if newAcc.Plain != nil {
if newAcc.Plain.Name == "" {
newAcc.Plain.Name = acc.Plain.Name
}
acc.Plain = newAcc.Plain
}
if newAcc.Enc != nil {
if newAcc.Enc.Name == "" {
newAcc.Enc.Name = acc.Enc.Name
}
acc.Enc = newAcc.Enc
}
return accs
}
}
case *EnvPlainAcc:
for _, acc := range accs {
if (acc.Enc != nil && newAcc.Username == acc.Enc.Username) ||
(acc.Plain != nil && newAcc.Username == acc.Plain.Username) {
if newAcc.Name == "" {
newAcc.Name = acc.Plain.Name
}
acc.Plain = newAcc
return accs
}
}
accs = append(accs, &EnvAcc{Plain: newAcc})
case *EnvEncAcc:
for _, acc := range accs {
if (acc.Plain != nil && newAcc.Username == acc.Plain.Username) ||
(acc.Enc != nil && newAcc.Username == acc.Enc.Username) {
if newAcc.Name == "" {
newAcc.Name = acc.Enc.Name
}
acc.Enc = newAcc
return accs
}
}
accs = append(accs, &EnvAcc{Enc: newAcc})
}
return accs
}
func accsToFile(path string, accs []*EnvAcc) error {
newBuf := new(bytes.Buffer)
for _, acc := range accs {
if acc.Plain != nil {
line := fmt.Sprintf("INSTAGRAM_ACT_%s=\"%s:%s\"\n", acc.Plain.Name, acc.Plain.Username, acc.Plain.Password)
_, err := newBuf.WriteString(line)
if err != nil {
return err
}
}
if acc.Enc != nil {
encLine := fmt.Sprintf("INSTAGRAM_BASE64_%s=\"%s\"\n\n", acc.Enc.Name, acc.Enc.Base64)
_, err := newBuf.WriteString(encLine)
if err != nil {
return err
}
}
}
if err := os.WriteFile(path, newBuf.Bytes(), 0o644); err != nil {
return err
}
return nil
}
func (acc *Account) GetEnvEncAcc() (*EnvEncAcc, error) {
b, err := acc.insta.ExportAsBase64String()
return &EnvEncAcc{
Username: acc.Username,
Base64: b,
}, err
}