Files
2025-03-20 23:12:55 +03:00

121 lines
2.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package account
import (
"encoding/json"
"password/encrypter"
"password/output"
"strings"
"time"
"github.com/fatih/color"
)
type ByteReader interface {
Read() ([]byte, error)
}
type ByteWriter interface {
Write([]byte)
}
// embedded interface
type Db interface {
ByteReader
ByteWriter
}
type Vault struct {
Accounts []Account `json:"accounts"`
UpdatedAt time.Time `json:"updatedAt"`
}
type VaultWithDb struct {
Vault
db Db
enc encrypter.Encrypter
}
func NewVault(db Db, enc encrypter.Encrypter) *VaultWithDb {
file, err := db.Read()
if err != nil {
return &VaultWithDb{
Vault: Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
},
db: db,
enc: enc,
}
}
data := enc.Decrypt(file)
var vault Vault
err = json.Unmarshal(data, &vault)
color.Cyan("Найдено аккаунтов - %d", len(vault.Accounts))
if err != nil {
output.PrintError("Не удалось разобрать файл data.json")
return &VaultWithDb{
Vault: Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
},
db: db,
enc: enc,
}
}
return &VaultWithDb{
Vault: vault,
db: db,
enc: enc,
}
}
func (vault *VaultWithDb) AddAccount(acc Account) {
vault.Accounts = append(vault.Accounts, acc)
vault.save()
}
func (vault *Vault) ToBytes() ([]byte, error) {
file, err := json.Marshal(vault)
if err != nil {
return nil, err
}
return file, nil
}
func (vault *VaultWithDb) FindAccounts(str string, checker func(Account, string) bool) []Account {
var accounts []Account
for _, account := range vault.Accounts {
isMatched := checker(account, str)
if isMatched {
accounts = append(accounts, account)
}
}
return accounts
}
func (vault *VaultWithDb) DeleteAccountByUrl(url string) bool {
var accounts []Account
isDeleted := false
for _, account := range vault.Accounts {
isMatched := strings.Contains(account.Url, url)
if !isMatched {
accounts = append(accounts, account)
continue
}
isDeleted = true
}
vault.Accounts = accounts
vault.save()
return isDeleted
}
func (vault *VaultWithDb) save() {
vault.UpdatedAt = time.Now()
data, err := vault.Vault.ToBytes()
encData := vault.enc.Encrypt(data)
if err != nil {
output.PrintError("Не удалось преобразовать")
}
vault.db.Write(encData)
}