Verified Commit d635cd55 authored by Vladimir Hodakov's avatar Vladimir Hodakov 🔥
Browse files

Initial commit

parents
// Yandex Disk File Pusher
// Copyright (c) 2019 Vladimir "fat0troll" Hodakov
package yandexv1
import (
"os"
"strings"
)
// authorize autorizes user and saves token to config
// Autorization made of two steps: providing user URL to create token and
// getting token from provided code
func authorize() {
if !checkAuth() {
baseURL := "https://oauth.yandex.ru/authorize?response_type=code&client_id={{ client_id }}"
baseURL += "&device_id={{ device_id }}&device_name=yapusher-cli&force_confirm=yes"
baseURL = strings.Replace(baseURL, "{{ client_id }}", YANDEX_APPID, 1)
baseURL = strings.Replace(baseURL, "{{ device_id }}", c.Config.DeviceID, 1)
dlog.Info().Msg("Please open in your browser this URL and authorize the app. After getting the code restart the app with -authCode param (see -h for details).")
dlog.Info().Msgf("Auth URL: %s", baseURL)
os.Exit(0)
}
}
// checkAuth detects if we have authorized already
func checkAuth() bool {
if c.Config.Token.AccessToken != "" {
return true
}
return false
}
// Yandex Disk File Pusher
// Copyright (c) 2019 Vladimir "fat0troll" Hodakov
package yandexv1
import (
"github.com/fat0troll/yapusher/internal/context"
"github.com/rs/zerolog"
"gitlab.com/pztrn/flagger"
)
const YANDEX_APPID = "7d8a0561fdc44c05bb6695b464403f9c"
var (
c *context.Context
dlog zerolog.Logger
)
// New initializes package
func New(cc *context.Context) {
c = cc
dlog = c.Logger.With().Str("domain", "yandex").Int("version", 1).Logger()
_ = c.Flagger.AddFlag(&flagger.Flag{
Name: "authCode",
Description: "Auth code obtained from Yandex (seven digits).",
Type: "int",
DefaultValue: 0000000,
})
dlog.Info().Msg("Domain initialized")
}
// Process handles authorization and files
func Process() {
if !checkAuth() {
authorize()
}
}
module github.com/fat0troll/yapusher
go 1.12
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f
github.com/rs/zerolog v1.13.0
github.com/stretchr/testify v1.3.0 // indirect
gitlab.com/pztrn/flagger v0.0.0-20190122123836-d429d7149cc9
gitlab.com/pztrn/go-uuid v0.0.0-20190208164458-d6cc46783d2b
)
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f h1:dKccXx7xA56UNqOcFIbuqFjAWPVtP688j5QMgmo6OHU=
github.com/kirsle/configdir v0.0.0-20170128060238-e45d2f54772f/go.mod h1:4rEELDSfUAlBSyUjPG0JnaNGjf13JySHFeRdD/3dLP0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/zerolog v1.13.0 h1:hSNcYHyxDWycfePW7pUI8swuFkcSMPKh3E63Pokg1Hk=
github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
gitlab.com/pztrn/flagger v0.0.0-20190122123836-d429d7149cc9 h1:qLlIZybSEr3MSCaE+cJZpT6O/1q3IsBPV7GcZJc05vs=
gitlab.com/pztrn/flagger v0.0.0-20190122123836-d429d7149cc9/go.mod h1:2cxOO1JFwNeKmT/icFNkUOPzQnG+qeMXURKeVFsuQA8=
gitlab.com/pztrn/go-uuid v0.0.0-20190208164458-d6cc46783d2b h1:KlXJDsOy0s6g6hd/0iNnyHcgfGWwavWGDewGu3S7waA=
gitlab.com/pztrn/go-uuid v0.0.0-20190208164458-d6cc46783d2b/go.mod h1:+3ulqQxYefYuKiYcnYRVCTRq0W1JTTMXGqibizAbIRI=
// Yandex Disk File Pusher
// Copyright (c) 2019 Vladimir "fat0troll" Hodakov
package config
type Config struct {
DeviceID string `json:"device_id"`
Token Token `json:"token,omitempty"`
}
// Yandex Disk File Pusher
// Copyright (c) 2019 Vladimir "fat0troll" Hodakov
package config
type Token struct {
TokenType string `json:"token_type"`
AccessToken string `json:"access_token"`
ExpireTime int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
}
// Yandex Disk File Pusher
// Copyright (c) 2019 Vladimir "fat0troll" Hodakov
package context
import (
"encoding/json"
"fmt"
"github.com/kirsle/configdir"
"github.com/rs/zerolog"
"gitlab.com/pztrn/flagger"
"gitlab.com/pztrn/go-uuid"
"log"
"os"
"path/filepath"
"runtime"
)
// getMemoryUsage returns memory usage for logger.
func (c *Context) getMemoryUsage(e *zerolog.Event, level zerolog.Level, message string) {
var m runtime.MemStats
runtime.ReadMemStats(&m)
e.Str("memalloc", fmt.Sprintf("%dMB", m.Alloc/1024/1024))
e.Str("memsys", fmt.Sprintf("%dMB", m.Sys/1024/1024))
e.Str("numgc", fmt.Sprintf("%d", m.NumGC))
}
// generateDefaultConfig generates new config on first run
func (c *Context) generateDefaultConfig() {
newDeviceID, _ := uuid.NewV4()
c.Config.DeviceID = newDeviceID.String()
}
// initFlagger initializes flags parser
func (c *Context) initFlagger() {
c.Flagger = flagger.New("Yandex Disk Files Pusher", flagger.LoggerInterface(log.New(os.Stdout, "", log.Lshortfile)))
c.Flagger.Initialize()
}
// Init is an initialization function for core context
// Without these parts of the application we can't start at all
func (c *Context) Init() {
c.initFlagger()
c.Logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
c.Logger = c.Logger.Hook(zerolog.HookFunc(c.getMemoryUsage))
c.Logger.Info().Str("version", VERSION).Msg("yapusher is starting")
dlog = c.Logger.With().Str("domain", "context").Logger()
}
func (c *Context) InitConfig() {
configPath := configdir.LocalConfig("yapusher")
err := configdir.MakePath(configPath)
if err != nil {
dlog.Fatal().Err(err).Str("config directory", configPath).Msg("Failed to obtain config path")
}
dlog.Debug().Str("config directory", configPath).Msg("Got config directory")
configFile := filepath.Join(configPath, "settings.json")
if _, err = os.Stat(configFile); os.IsNotExist(err) {
// Generating new config on first run
dlog.Debug().Msg("Generating new config")
c.generateDefaultConfig()
fh, err := os.Create(configFile)
if err != nil {
dlog.Fatal().Err(err).Msg("Failed to create config file")
}
defer fh.Close()
encoder := json.NewEncoder(fh)
err = encoder.Encode(c.Config)
if err != nil {
dlog.Fatal().Err(err).Msg("Failed to encode config")
}
} else {
dlog.Debug().Msg("Using existing config")
fh, err := os.Open(configFile)
if err != nil {
dlog.Fatal().Err(err).Msg("Failed to read config file")
}
defer fh.Close()
decoder := json.NewDecoder(fh)
decoder.Decode(c.Config)
if err != nil {
dlog.Fatal().Err(err).Msg("Failed to decode config")
}
}
}
// Yandex Disk File Pusher
// Copyright (c) 2019 Vladimir "fat0troll" Hodakov
package context
import (
"github.com/fat0troll/yapusher/internal/config"
"github.com/rs/zerolog"
"gitlab.com/pztrn/flagger"
)
// VERSION is the current app version
const VERSION = "0.0.1"
var (
dlog zerolog.Logger
)
// Context is the main application context.
type Context struct {
Config config.Config
Flagger *flagger.Flagger
Logger zerolog.Logger
}
// New creates new Context
func New() *Context {
c := &Context{}
return c
}
// Yandex Disk File Pusher
// Copyright (c) 2019 Vladimir "fat0troll" Hodakov
package main
import (
"github.com/fat0troll/yapusher/domains/yandex/v1"
"github.com/fat0troll/yapusher/internal/context"
)
func main() {
c := context.New()
c.Init()
c.InitConfig()
// Initializing domains
yandexv1.New(c)
// Parsing app flags
c.Flagger.Parse()
// Authorizing to Yandex
yandexv1.Process()
}
The MIT License (MIT)
Copyright (c) 2017 Noah Petherbridge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# ConfigDir for Go
This library provides a cross platform means of detecting the system's
configuration directories so that your Go app can store config files in a
standard location. For Linux and other Unixes (BSD, etc.) this means using the
[Freedesktop.org XDG Base Directory Specification][1] (0.8), and for Windows
and macOS it uses their standard directories.
This is a simple no-nonsense module that just gives you the path names to do
with as you please. You can either get the bare root config path, or get a
path with any number of names suffixed onto it for vendor- or
application-specific namespacing.
For the impatient, the directories this library can return tend to be like
the following:
| | **System-wide Configuration** |
|---------|-----------------------------------------------------|
| Windows | `%PROGRAMDATA%` or `C:\ProgramData` |
| Linux | `$XDG_CONFIG_DIRS` or `/etc/xdg` |
| macOS | `/Library/Application Support` |
| | **User-level Configuration** |
| Windows | `%APPDATA%` or `C:\Users\%USER%\AppData\Roaming` |
| Linux | `$XDG_CONFIG_HOME` or `$HOME/.config` |
| macOS | `$HOME/Library/Application Support` |
| | **User-level Cache Folder** |
| Windows | `%LOCALAPPDATA%` or `C:\Users\%USER%\AppData\Local` |
| Linux | `$XDG_CACHE_HOME` or `$HOME/.cache` |
| macOS | `$HOME/Library/Caches` |
## Quick Start
```go
// A common use case is to get a private config folder for your app to
// place its settings files into, that are specific to the local user.
configPath := configdir.LocalConfig("my-app")
err := configdir.MakePath(configPath) // Ensure it exists.
if err != nil {
panic(err)
}
// Deal with a JSON configuration file in that folder.
configFile := filepath.Join(configPath, "settings.json")
type AppSettings struct {
Username string `json:"username"`
Password string `json:"password"`
}
var settings AppSettings
// Does the file not exist?
if _, err = os.Stat(configFile); os.IsNotExist(err) {
// Create the new config file.
settings = AppSettings{"MyUser", "MyPassword"}
fh, err := os.Create(configFile)
if err != nil {
panic(err)
}
defer fh.Close()
encoder := json.NewEncoder(fh)
encoder.Encode(&settings)
} else {
// Load the existing file.
fh, err := os.Open(configFile)
if err != nil {
panic(err)
}
defer fh.Close()
decoder := json.NewDecoder(fh)
decoder.Decode(&settings)
}
```
## Documentation
Package documentation is available at
<https://godoc.org/github.com/kirsle/configdir>
## Author
Noah Petherbridge, [@kirsle](https://github.com/kirsle)
## License
MIT
[1]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-0.8.html
[2]: https://github.com/shibukawa/configdir
package configdir
import "os"
var (
systemConfig []string
localConfig string
localCache string
)
func findPaths() {
systemConfig = []string{"/Library/Application Support"}
localConfig = os.Getenv("HOME") + "/Library/Application Support"
localCache = os.Getenv("HOME") + "/Library/Caches"
}
package configdir
import "os"
var (
systemConfig []string
localConfig string
localCache string
)
func findPaths() {
systemConfig = []string{os.Getenv("PROGRAMDATA")}
localConfig = os.Getenv("APPDATA")
localCache = os.Getenv("LOCALAPPDATA")
}
// +build !windows,!darwin
package configdir
import (
"os"
"path/filepath"
"strings"
)
var (
systemConfig []string
localConfig string
localCache string
)
func findPaths() {
// System-wide configuration.
if os.Getenv("XDG_CONFIG_DIRS") != "" {
systemConfig = strings.Split(os.Getenv("XDG_CONFIG_DIRS"), ":")
} else {
systemConfig = []string{"/etc/xdg"}
}
// Local user configuration.
if os.Getenv("XDG_CONFIG_HOME") != "" {
localConfig = os.Getenv("XDG_CONFIG_HOME")
} else {
localConfig = filepath.Join(os.Getenv("HOME"), ".config")
}
// Local user cache.
if os.Getenv("XDG_CACHE_HOME") != "" {
localCache = os.Getenv("XDG_CACHE_HOME")
} else {
localCache = filepath.Join(os.Getenv("HOME"), ".cache")
}
}
package configdir
import (
"os"
"path/filepath"
)
// VERSION is the semantic version number of the configdir library.
const VERSION = "0.1.0"
func init() {
findPaths()
}
// Refresh will rediscover the config paths, checking current environment
// variables again.
//
// This function is automatically called when the program initializes. If you
// change the environment variables at run-time, though, you may call the
// Refresh() function to reevaluate the config paths.
func Refresh() {
findPaths()
}
// SystemConfig returns the system-wide configuration paths, with optional path
// components added to the end for vendor/application-specific settings.
func SystemConfig(folder ...string) []string {
if len(folder) == 0 {
return systemConfig
}
var paths []string
for _, root := range systemConfig {
p := append([]string{root}, filepath.Join(folder...))
paths = append(paths, filepath.Join(p...))
}
return paths
}
// LocalConfig returns the local user configuration path, with optional
// path components added to the end for vendor/application-specific settings.
func LocalConfig(folder ...string) string {
if len(folder) == 0 {
return localConfig
}
return filepath.Join(localConfig, filepath.Join(folder...))
}
// LocalCache returns the local user cache folder, with optional path
// components added to the end for vendor/application-specific settings.
func LocalCache(folder ...string) string {
if len(folder) == 0 {
return localCache
}
return filepath.Join(localCache, filepath.Join(folder...))
}
// DefaultFileMode controls the default permissions on any paths created by
// using MakePath.
var DefaultFileMode = os.FileMode(0755)
// MakePath ensures that the full path you wanted, including vendor or
// application-specific components, exists. You can give this the output of
// any of the config path functions (SystemConfig, LocalConfig or LocalCache).
//
// In the event that the path function gives multiple answers, e.g. for
// SystemConfig, MakePath() will only attempt to create the sub-folders on
// the *first* path found. If this isn't what you want, you may want to just
// use the os.MkdirAll() functionality directly.
func MakePath(paths ...string) error {
if len(paths) >= 1 {
err := os.MkdirAll(paths[0], DefaultFileMode)
if err != nil {
return err
}
}
return nil
}
/*
Package configdir provides a cross platform means of detecting the system's
configuration directories.
This makes it easy to program your Go app to store its configuration files in
a standard location relevant to the host operating system. For Linux and some
other Unixes (like BSD) this means following the Freedesktop.org XDG Base
Directory Specification 0.8, and for Windows and macOS it uses their standard
directories.
This is a simple no-nonsense module that just gives you the paths, with
optional components tacked on the end for vendor- or app-specific namespacing.
It also provides a convenience function to call `os.MkdirAll()` on the paths to
ensure they exist and are ready for you to read and write files in.
Standard Global Configuration Paths
* Linux: $XDG_CONFIG_DIRS or "/etc/xdg"
* Windows: %PROGRAMDATA% or "C:\\ProgramData"
* macOS: /Library/Application Support
Standard User-Specific Configuration Paths
* Linux: $XDG_CONFIG_HOME or "$HOME/.config"
* Windows: %APPDATA% or "C:\\Users\\%USER%\\AppData\\Roaming"
* macOS: $HOME/Library/Application Support
Standard User-Specific Cache Paths
* Linux: $XDG_CACHE_HOME or "$HOME/.cache"
* Windows: %LOCALAPPDATA% or "C:\\Users\\%USER%\\AppData\\Local"
* macOS: $HOME/Library/Caches
[1]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-0.8.html
*/
package configdir
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
tmp
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go