<commit_before>package zwave

type NodeProtocolInfoResponse struct {
	CommandId           byte
	Capability          byte
	Security            byte
	BasicDeviceClass    byte
	GenericDeviceClass  byte
	SpecificDeviceClass byte
}

func ParseNodeProtocolInfoResponse(payload []byte) *NodeProtocolInfoResponse {
	val := &NodeProtocolInfoResponse{
		CommandId:           payload[0],
		Capability:          payload[1],
		Security:            payload[2],
		BasicDeviceClass:    payload[4],
		GenericDeviceClass:  payload[5],
		SpecificDeviceClass: payload[6],
	}

	return val
}

func (n *NodeProtocolInfoResponse) IsListening() bool {
	return n.Capability&0x80 == 0x80
}

func (n *NodeProtocolInfoResponse) GetBasicDeviceClassName() string {
	return GetBasicTypeName(n.BasicDeviceClass)
}

func (n *NodeProtocolInfoResponse) GetGenericDeviceClassName() string {
	return GetGenericTypeName(n.BasicDeviceClass)
}

func (n *NodeProtocolInfoResponse) GetSpecificDeviceClassName() string {
	return GetSpecificTypeName(n.BasicDeviceClass, n.SpecificDeviceClass)
}
<commit_msg>fix node proto info device class<commit_after>package zwave

type NodeProtocolInfoResponse struct {
	CommandId           byte
	Capability          byte
	Security            byte
	BasicDeviceClass    byte
	GenericDeviceClass  byte
	SpecificDeviceClass byte
}

func ParseNodeProtocolInfoResponse(payload []byte) *NodeProtocolInfoResponse {
	val := &NodeProtocolInfoResponse{
		CommandId:           payload[0],
		Capability:          payload[1],
		Security:            payload[2],
		BasicDeviceClass:    payload[4],
		GenericDeviceClass:  payload[5],
		SpecificDeviceClass: payload[6],
	}

	return val
}

func (n *NodeProtocolInfoResponse) IsListening() bool {
	return n.Capability&0x80 == 0x80
}

func (n *NodeProtocolInfoResponse) GetBasicDeviceClassName() string {
	return GetBasicTypeName(n.BasicDeviceClass)
}

func (n *NodeProtocolInfoResponse) GetGenericDeviceClassName() string {
	return GetGenericTypeName(n.GenericDeviceClass)
}

func (n *NodeProtocolInfoResponse) GetSpecificDeviceClassName() string {
	return GetSpecificTypeName(n.GenericDeviceClass, n.SpecificDeviceClass)
}
<|endoftext|>


<commit_before>package auth

import (
	"context"
	"net/http"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/passwordhistory"
	"github.com/skygeario/skygear-server/pkg/core/time"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/forgotpwdemail"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/hook"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/userverify"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/welcemail"

	"github.com/sirupsen/logrus"
	authAudit "github.com/skygeario/skygear-server/pkg/auth/dependency/audit"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/authnsession"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/mfa"
	mfaPQ "github.com/skygeario/skygear-server/pkg/auth/dependency/mfa/pq"
	pqPWHistory "github.com/skygeario/skygear-server/pkg/auth/dependency/passwordhistory/pq"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal/customtoken"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal/oauth"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal/password"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/sso"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"
	authTemplate "github.com/skygeario/skygear-server/pkg/auth/template"
	"github.com/skygeario/skygear-server/pkg/core/async"
	"github.com/skygeario/skygear-server/pkg/core/audit"
	coreAuth "github.com/skygeario/skygear-server/pkg/core/auth"
	"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
	"github.com/skygeario/skygear-server/pkg/core/auth/session"
	redisSession "github.com/skygeario/skygear-server/pkg/core/auth/session/redis"
	"github.com/skygeario/skygear-server/pkg/core/config"
	"github.com/skygeario/skygear-server/pkg/core/db"
	"github.com/skygeario/skygear-server/pkg/core/logging"
	"github.com/skygeario/skygear-server/pkg/core/mail"
	"github.com/skygeario/skygear-server/pkg/core/template"
)

type DependencyMap struct {
	TemplateEngine    *template.Engine
	AsyncTaskExecutor *async.Executor
	UseInsecureCookie bool
}

// Provide provides dependency instance by name
// nolint: gocyclo, golint
func (m DependencyMap) Provide(
	dependencyName string,
	request *http.Request,
	ctx context.Context,
	requestID string,
	tConfig config.TenantConfiguration,
) interface{} {
	newLogger := func(name string) *logrus.Entry {
		formatter := logging.CreateMaskFormatter(tConfig.DefaultSensitiveLoggerValues(), &logrus.TextFormatter{})
		return logging.CreateLoggerWithRequestID(requestID, name, formatter)
	}

	newLoggerFactory := func() logging.Factory {
		formatter := logging.CreateMaskFormatter(tConfig.DefaultSensitiveLoggerValues(), &logrus.TextFormatter{})
		return logging.NewFactory(request, formatter)
	}

	newSQLBuilder := func() db.SQLBuilder {
		return db.NewSQLBuilder("auth", tConfig.AppConfig.DatabaseSchema, tConfig.AppID)
	}

	newSQLExecutor := func() db.SQLExecutor {
		return db.NewSQLExecutor(ctx, db.NewContextWithContext(ctx, tConfig))
	}

	newTimeProvider := func() time.Provider {
		return time.NewProvider()
	}

	newAuthContext := func() coreAuth.ContextGetter {
		return coreAuth.NewContextGetterWithContext(ctx)
	}

	newPasswordHistoryStore := func() passwordhistory.Store {
		return pqPWHistory.NewPasswordHistoryStore(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("auth_password_history"),
		)
	}

	newTemplateEngine := func() *template.Engine {
		return authTemplate.NewEngineWithConfig(m.TemplateEngine, tConfig)
	}

	newAuthInfoStore := func() authinfo.Store {
		return coreAuth.NewDefaultAuthInfoStore(ctx, tConfig)
	}

	newUserProfileStore := func() userprofile.Store {
		return userprofile.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("auth_user_profile"),
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	// TODO:
	// from tConfig
	isPasswordHistoryEnabled := func() bool {
		return tConfig.UserConfig.UserAudit.Password.HistorySize > 0 ||
			tConfig.UserConfig.UserAudit.Password.HistoryDays > 0
	}

	newPasswordAuthProvider := func() password.Provider {
		return password.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("provider_password"),
			tConfig.UserConfig.Auth.LoginIDKeys,
			tConfig.UserConfig.Auth.AllowedRealms,
			isPasswordHistoryEnabled(),
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	newCustomTokenAuthProvider := func() customtoken.Provider {
		return customtoken.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("provider_custom_token"),
			tConfig.UserConfig.SSO.CustomToken,
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	newOAuthAuthProvider := func() oauth.Provider {
		return oauth.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("provider_oauth"),
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	newHookProvider := func() hook.Provider {
		return hook.NewProvider(
			requestID,
			request,
			hook.NewStore(newSQLBuilder(), newSQLExecutor()),
			newAuthContext(),
			newTimeProvider(),
			newAuthInfoStore(),
			newUserProfileStore(),
			hook.NewDeliverer(
				&tConfig,
				newTimeProvider(),
				hook.NewMutator(
					&tConfig.UserConfig.UserVerification,
					newPasswordAuthProvider(),
					newAuthInfoStore(),
					newUserProfileStore(),
				),
			),
		)
	}

	newSessionProvider := func() session.Provider {
		return session.NewProvider(
			request,
			redisSession.NewStore(ctx, tConfig.AppID, newTimeProvider()),
			redisSession.NewEventStore(ctx, tConfig.AppID),
			newAuthContext(),
			tConfig.UserConfig.Clients,
		)
	}

	newIdentityProvider := func() principal.IdentityProvider {
		return principal.NewIdentityProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newCustomTokenAuthProvider(),
			newOAuthAuthProvider(),
			newPasswordAuthProvider(),
		)
	}

	newSessionWriter := func() session.Writer {
		return session.NewWriter(
			newAuthContext(),
			tConfig.UserConfig.Clients,
			tConfig.UserConfig.MFA,
			m.UseInsecureCookie,
		)
	}

	newMFAProvider := func() mfa.Provider {
		return mfa.NewProvider(
			mfaPQ.NewStore(
				tConfig.UserConfig.MFA,
				newSQLBuilder(),
				newSQLExecutor(),
				newTimeProvider(),
			),
			tConfig.UserConfig.MFA,
			newTimeProvider(),
		)
	}

	switch dependencyName {
	case "AuthContextGetter":
		return newAuthContext()
	case "AuthContextSetter":
		return coreAuth.NewContextSetterWithContext(ctx)
	case "TxContext":
		return db.NewTxContextWithContext(ctx, tConfig)
	case "LoggerFactory":
		return newLoggerFactory()
	case "SessionProvider":
		return newSessionProvider()
	case "SessionWriter":
		return newSessionWriter()
	case "MFAProvider":
		return newMFAProvider()
	case "AuthnSessionProvider":
		return authnsession.NewProvider(
			newAuthContext(),
			tConfig.UserConfig.MFA,
			tConfig.UserConfig.Auth.AuthenticationSession,
			newTimeProvider(),
			newMFAProvider(),
			newAuthInfoStore(),
			newSessionProvider(),
			newSessionWriter(),
			newIdentityProvider(),
			newHookProvider(),
			newUserProfileStore(),
		)
	case "AuthInfoStore":
		return newAuthInfoStore()
	case "PasswordChecker":
		return &authAudit.PasswordChecker{
			PwMinLength:         tConfig.UserConfig.UserAudit.Password.MinLength,
			PwUppercaseRequired: tConfig.UserConfig.UserAudit.Password.UppercaseRequired,
			PwLowercaseRequired: tConfig.UserConfig.UserAudit.Password.LowercaseRequired,
			PwDigitRequired:     tConfig.UserConfig.UserAudit.Password.DigitRequired,
			PwSymbolRequired:    tConfig.UserConfig.UserAudit.Password.SymbolRequired,
			PwMinGuessableLevel: tConfig.UserConfig.UserAudit.Password.MinimumGuessableLevel,
			PwExcludedKeywords:  tConfig.UserConfig.UserAudit.Password.ExcludedKeywords,
			//PwExcludedFields:       tConfig.UserConfig.UserAudit.Password.ExcludedFields,
			PwHistorySize:          tConfig.UserConfig.UserAudit.Password.HistorySize,
			PwHistoryDays:          tConfig.UserConfig.UserAudit.Password.HistoryDays,
			PasswordHistoryEnabled: tConfig.UserConfig.UserAudit.Password.HistorySize > 0 || tConfig.UserConfig.UserAudit.Password.HistoryDays > 0,
			PasswordHistoryStore:   newPasswordHistoryStore(),
		}
	case "PwHousekeeper":
		return authAudit.NewPwHousekeeper(
			newPasswordHistoryStore(),
			newLogger("audit"),
			tConfig.UserConfig.UserAudit.Password.HistorySize,
			tConfig.UserConfig.UserAudit.Password.HistoryDays,
			isPasswordHistoryEnabled(),
		)
	case "PasswordAuthProvider":
		return newPasswordAuthProvider()
	case "CustomTokenAuthProvider":
		return newCustomTokenAuthProvider()
	case "HandlerLogger":
		return newLogger("handler")
	case "UserProfileStore":
		return newUserProfileStore()
	case "ForgotPasswordEmailSender":
		return forgotpwdemail.NewDefaultSender(tConfig, mail.NewDialer(tConfig.AppConfig.SMTP), newTemplateEngine())
	case "TestForgotPasswordEmailSender":
		return forgotpwdemail.NewDefaultTestSender(tConfig, mail.NewDialer(tConfig.AppConfig.SMTP))
	case "ForgotPasswordCodeGenerator":
		return &forgotpwdemail.CodeGenerator{MasterKey: tConfig.UserConfig.MasterKey}
	case "ForgotPasswordSecureMatch":
		return tConfig.UserConfig.ForgotPassword.SecureMatch
	case "ResetPasswordHTMLProvider":
		return forgotpwdemail.NewResetPasswordHTMLProvider(tConfig.UserConfig.ForgotPassword, newTemplateEngine())
	case "WelcomeEmailEnabled":
		return tConfig.UserConfig.WelcomeEmail.Enabled
	case "WelcomeEmailDestination":
		return tConfig.UserConfig.WelcomeEmail.Destination
	case "WelcomeEmailSender":
		return welcemail.NewDefaultSender(tConfig, mail.NewDialer(tConfig.AppConfig.SMTP), newTemplateEngine())
	case "TestWelcomeEmailSender":
		return welcemail.NewDefaultTestSender(tConfig, mail.NewDialer(tConfig.AppConfig.SMTP))
	case "IFrameHTMLProvider":
		return sso.NewIFrameHTMLProvider(tConfig.UserConfig.SSO.OAuth.APIEndpoint())
	case "UserVerifyCodeSenderFactory":
		return userverify.NewDefaultUserVerifyCodeSenderFactory(tConfig, newTemplateEngine())
	case "UserVerifyTestCodeSenderFactory":
		return userverify.NewDefaultUserVerifyTestCodeSenderFactory(tConfig, newTemplateEngine())
	case "AutoSendUserVerifyCodeOnSignup":
		return tConfig.UserConfig.UserVerification.AutoSendOnSignup
	case "UserVerifyLoginIDKeys":
		return tConfig.UserConfig.UserVerification.LoginIDKeys
	case "UserVerificationProvider":
		return userverify.NewProvider(
			userverify.NewCodeGenerator(tConfig),
			userverify.NewSafeStore(
				newSQLBuilder(),
				newSQLExecutor(),
				newLogger("verify_code"),
				db.NewSafeTxContextWithContext(ctx, tConfig),
			),
			tConfig.UserConfig.UserVerification,
			newTimeProvider(),
		)
	case "VerifyHTMLProvider":
		return userverify.NewVerifyHTMLProvider(tConfig.UserConfig.UserVerification, newTemplateEngine())
	case "AuditTrail":
		trail, err := audit.NewTrail(tConfig.UserConfig.UserAudit.Enabled, tConfig.UserConfig.UserAudit.TrailHandlerURL)
		if err != nil {
			panic(err)
		}
		return trail
	case "SSOProviderFactory":
		return sso.NewProviderFactory(tConfig)
	case "OAuthAuthProvider":
		return newOAuthAuthProvider()
	case "IdentityProvider":
		return newIdentityProvider()
	case "AuthHandlerHTMLProvider":
		return sso.NewAuthHandlerHTMLProvider(tConfig.UserConfig.SSO.OAuth.APIEndpoint())
	case "AsyncTaskQueue":
		return async.NewQueue(ctx, requestID, tConfig, m.AsyncTaskExecutor)
	case "HookProvider":
		return newHookProvider()
	case "CustomTokenConfiguration":
		return tConfig.UserConfig.SSO.CustomToken
	case "OAuthConfiguration":
		return tConfig.UserConfig.SSO.OAuth
	case "AuthConfiguration":
		return tConfig.UserConfig.Auth
	case "MFAConfiguration":
		return tConfig.UserConfig.MFA
	default:
		return nil
	}
}
<commit_msg>Replace repeating construction with closure<commit_after>package auth

import (
	"context"
	"net/http"

	"github.com/go-gomail/gomail"
	"github.com/sirupsen/logrus"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/passwordhistory"
	"github.com/skygeario/skygear-server/pkg/core/time"

	"github.com/skygeario/skygear-server/pkg/auth/dependency/forgotpwdemail"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/hook"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/userverify"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/welcemail"

	authAudit "github.com/skygeario/skygear-server/pkg/auth/dependency/audit"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/authnsession"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/mfa"
	mfaPQ "github.com/skygeario/skygear-server/pkg/auth/dependency/mfa/pq"
	pqPWHistory "github.com/skygeario/skygear-server/pkg/auth/dependency/passwordhistory/pq"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal/customtoken"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal/oauth"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/principal/password"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/sso"
	"github.com/skygeario/skygear-server/pkg/auth/dependency/userprofile"
	authTemplate "github.com/skygeario/skygear-server/pkg/auth/template"
	"github.com/skygeario/skygear-server/pkg/core/async"
	"github.com/skygeario/skygear-server/pkg/core/audit"
	coreAuth "github.com/skygeario/skygear-server/pkg/core/auth"
	"github.com/skygeario/skygear-server/pkg/core/auth/authinfo"
	"github.com/skygeario/skygear-server/pkg/core/auth/session"
	redisSession "github.com/skygeario/skygear-server/pkg/core/auth/session/redis"
	"github.com/skygeario/skygear-server/pkg/core/config"
	"github.com/skygeario/skygear-server/pkg/core/db"
	"github.com/skygeario/skygear-server/pkg/core/logging"
	"github.com/skygeario/skygear-server/pkg/core/mail"
	"github.com/skygeario/skygear-server/pkg/core/sms"
	"github.com/skygeario/skygear-server/pkg/core/template"
)

type DependencyMap struct {
	TemplateEngine    *template.Engine
	AsyncTaskExecutor *async.Executor
	UseInsecureCookie bool
}

// Provide provides dependency instance by name
// nolint: gocyclo, golint
func (m DependencyMap) Provide(
	dependencyName string,
	request *http.Request,
	ctx context.Context,
	requestID string,
	tConfig config.TenantConfiguration,
) interface{} {
	newLogger := func(name string) *logrus.Entry {
		formatter := logging.CreateMaskFormatter(tConfig.DefaultSensitiveLoggerValues(), &logrus.TextFormatter{})
		return logging.CreateLoggerWithRequestID(requestID, name, formatter)
	}

	newLoggerFactory := func() logging.Factory {
		formatter := logging.CreateMaskFormatter(tConfig.DefaultSensitiveLoggerValues(), &logrus.TextFormatter{})
		return logging.NewFactory(request, formatter)
	}

	newSQLBuilder := func() db.SQLBuilder {
		return db.NewSQLBuilder("auth", tConfig.AppConfig.DatabaseSchema, tConfig.AppID)
	}

	newSQLExecutor := func() db.SQLExecutor {
		return db.NewSQLExecutor(ctx, db.NewContextWithContext(ctx, tConfig))
	}

	newTimeProvider := func() time.Provider {
		return time.NewProvider()
	}

	newAuthContext := func() coreAuth.ContextGetter {
		return coreAuth.NewContextGetterWithContext(ctx)
	}

	newPasswordHistoryStore := func() passwordhistory.Store {
		return pqPWHistory.NewPasswordHistoryStore(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("auth_password_history"),
		)
	}

	newTemplateEngine := func() *template.Engine {
		return authTemplate.NewEngineWithConfig(m.TemplateEngine, tConfig)
	}

	newAuthInfoStore := func() authinfo.Store {
		return coreAuth.NewDefaultAuthInfoStore(ctx, tConfig)
	}

	newUserProfileStore := func() userprofile.Store {
		return userprofile.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("auth_user_profile"),
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	// TODO:
	// from tConfig
	isPasswordHistoryEnabled := func() bool {
		return tConfig.UserConfig.UserAudit.Password.HistorySize > 0 ||
			tConfig.UserConfig.UserAudit.Password.HistoryDays > 0
	}

	newPasswordAuthProvider := func() password.Provider {
		return password.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("provider_password"),
			tConfig.UserConfig.Auth.LoginIDKeys,
			tConfig.UserConfig.Auth.AllowedRealms,
			isPasswordHistoryEnabled(),
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	newCustomTokenAuthProvider := func() customtoken.Provider {
		return customtoken.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("provider_custom_token"),
			tConfig.UserConfig.SSO.CustomToken,
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	newOAuthAuthProvider := func() oauth.Provider {
		return oauth.NewSafeProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newLogger("provider_oauth"),
			db.NewSafeTxContextWithContext(ctx, tConfig),
		)
	}

	newHookProvider := func() hook.Provider {
		return hook.NewProvider(
			requestID,
			request,
			hook.NewStore(newSQLBuilder(), newSQLExecutor()),
			newAuthContext(),
			newTimeProvider(),
			newAuthInfoStore(),
			newUserProfileStore(),
			hook.NewDeliverer(
				&tConfig,
				newTimeProvider(),
				hook.NewMutator(
					&tConfig.UserConfig.UserVerification,
					newPasswordAuthProvider(),
					newAuthInfoStore(),
					newUserProfileStore(),
				),
			),
		)
	}

	newSessionProvider := func() session.Provider {
		return session.NewProvider(
			request,
			redisSession.NewStore(ctx, tConfig.AppID, newTimeProvider()),
			redisSession.NewEventStore(ctx, tConfig.AppID),
			newAuthContext(),
			tConfig.UserConfig.Clients,
		)
	}

	newIdentityProvider := func() principal.IdentityProvider {
		return principal.NewIdentityProvider(
			newSQLBuilder(),
			newSQLExecutor(),
			newCustomTokenAuthProvider(),
			newOAuthAuthProvider(),
			newPasswordAuthProvider(),
		)
	}

	newSessionWriter := func() session.Writer {
		return session.NewWriter(
			newAuthContext(),
			tConfig.UserConfig.Clients,
			tConfig.UserConfig.MFA,
			m.UseInsecureCookie,
		)
	}

	newMFAProvider := func() mfa.Provider {
		return mfa.NewProvider(
			mfaPQ.NewStore(
				tConfig.UserConfig.MFA,
				newSQLBuilder(),
				newSQLExecutor(),
				newTimeProvider(),
			),
			tConfig.UserConfig.MFA,
			newTimeProvider(),
		)
	}

	newMailDialer := func() *gomail.Dialer {
		return mail.NewDialer(tConfig.AppConfig.SMTP)
	}

	switch dependencyName {
	case "AuthContextGetter":
		return newAuthContext()
	case "AuthContextSetter":
		return coreAuth.NewContextSetterWithContext(ctx)
	case "TxContext":
		return db.NewTxContextWithContext(ctx, tConfig)
	case "LoggerFactory":
		return newLoggerFactory()
	case "SessionProvider":
		return newSessionProvider()
	case "SessionWriter":
		return newSessionWriter()
	case "MFAProvider":
		return newMFAProvider()
	case "AuthnSessionProvider":
		return authnsession.NewProvider(
			newAuthContext(),
			tConfig.UserConfig.MFA,
			tConfig.UserConfig.Auth.AuthenticationSession,
			newTimeProvider(),
			newMFAProvider(),
			newAuthInfoStore(),
			newSessionProvider(),
			newSessionWriter(),
			newIdentityProvider(),
			newHookProvider(),
			newUserProfileStore(),
		)
	case "AuthInfoStore":
		return newAuthInfoStore()
	case "PasswordChecker":
		return &authAudit.PasswordChecker{
			PwMinLength:         tConfig.UserConfig.UserAudit.Password.MinLength,
			PwUppercaseRequired: tConfig.UserConfig.UserAudit.Password.UppercaseRequired,
			PwLowercaseRequired: tConfig.UserConfig.UserAudit.Password.LowercaseRequired,
			PwDigitRequired:     tConfig.UserConfig.UserAudit.Password.DigitRequired,
			PwSymbolRequired:    tConfig.UserConfig.UserAudit.Password.SymbolRequired,
			PwMinGuessableLevel: tConfig.UserConfig.UserAudit.Password.MinimumGuessableLevel,
			PwExcludedKeywords:  tConfig.UserConfig.UserAudit.Password.ExcludedKeywords,
			//PwExcludedFields:       tConfig.UserConfig.UserAudit.Password.ExcludedFields,
			PwHistorySize:          tConfig.UserConfig.UserAudit.Password.HistorySize,
			PwHistoryDays:          tConfig.UserConfig.UserAudit.Password.HistoryDays,
			PasswordHistoryEnabled: tConfig.UserConfig.UserAudit.Password.HistorySize > 0 || tConfig.UserConfig.UserAudit.Password.HistoryDays > 0,
			PasswordHistoryStore:   newPasswordHistoryStore(),
		}
	case "PwHousekeeper":
		return authAudit.NewPwHousekeeper(
			newPasswordHistoryStore(),
			newLogger("audit"),
			tConfig.UserConfig.UserAudit.Password.HistorySize,
			tConfig.UserConfig.UserAudit.Password.HistoryDays,
			isPasswordHistoryEnabled(),
		)
	case "PasswordAuthProvider":
		return newPasswordAuthProvider()
	case "CustomTokenAuthProvider":
		return newCustomTokenAuthProvider()
	case "HandlerLogger":
		return newLogger("handler")
	case "UserProfileStore":
		return newUserProfileStore()
	case "ForgotPasswordEmailSender":
		return forgotpwdemail.NewDefaultSender(tConfig, newMailDialer(), newTemplateEngine())
	case "TestForgotPasswordEmailSender":
		return forgotpwdemail.NewDefaultTestSender(tConfig, newMailDialer())
	case "ForgotPasswordCodeGenerator":
		return &forgotpwdemail.CodeGenerator{MasterKey: tConfig.UserConfig.MasterKey}
	case "ForgotPasswordSecureMatch":
		return tConfig.UserConfig.ForgotPassword.SecureMatch
	case "ResetPasswordHTMLProvider":
		return forgotpwdemail.NewResetPasswordHTMLProvider(tConfig.UserConfig.ForgotPassword, newTemplateEngine())
	case "WelcomeEmailEnabled":
		return tConfig.UserConfig.WelcomeEmail.Enabled
	case "WelcomeEmailDestination":
		return tConfig.UserConfig.WelcomeEmail.Destination
	case "WelcomeEmailSender":
		return welcemail.NewDefaultSender(tConfig, newMailDialer(), newTemplateEngine())
	case "TestWelcomeEmailSender":
		return welcemail.NewDefaultTestSender(tConfig, newMailDialer())
	case "IFrameHTMLProvider":
		return sso.NewIFrameHTMLProvider(tConfig.UserConfig.SSO.OAuth.APIEndpoint())
	case "UserVerifyCodeSenderFactory":
		return userverify.NewDefaultUserVerifyCodeSenderFactory(tConfig, newTemplateEngine())
	case "UserVerifyTestCodeSenderFactory":
		return userverify.NewDefaultUserVerifyTestCodeSenderFactory(tConfig, newTemplateEngine())
	case "AutoSendUserVerifyCodeOnSignup":
		return tConfig.UserConfig.UserVerification.AutoSendOnSignup
	case "UserVerifyLoginIDKeys":
		return tConfig.UserConfig.UserVerification.LoginIDKeys
	case "UserVerificationProvider":
		return userverify.NewProvider(
			userverify.NewCodeGenerator(tConfig),
			userverify.NewSafeStore(
				newSQLBuilder(),
				newSQLExecutor(),
				newLogger("verify_code"),
				db.NewSafeTxContextWithContext(ctx, tConfig),
			),
			tConfig.UserConfig.UserVerification,
			newTimeProvider(),
		)
	case "VerifyHTMLProvider":
		return userverify.NewVerifyHTMLProvider(tConfig.UserConfig.UserVerification, newTemplateEngine())
	case "AuditTrail":
		trail, err := audit.NewTrail(tConfig.UserConfig.UserAudit.Enabled, tConfig.UserConfig.UserAudit.TrailHandlerURL)
		if err != nil {
			panic(err)
		}
		return trail
	case "SSOProviderFactory":
		return sso.NewProviderFactory(tConfig)
	case "OAuthAuthProvider":
		return newOAuthAuthProvider()
	case "IdentityProvider":
		return newIdentityProvider()
	case "AuthHandlerHTMLProvider":
		return sso.NewAuthHandlerHTMLProvider(tConfig.UserConfig.SSO.OAuth.APIEndpoint())
	case "AsyncTaskQueue":
		return async.NewQueue(ctx, requestID, tConfig, m.AsyncTaskExecutor)
	case "HookProvider":
		return newHookProvider()
	case "CustomTokenConfiguration":
		return tConfig.UserConfig.SSO.CustomToken
	case "OAuthConfiguration":
		return tConfig.UserConfig.SSO.OAuth
	case "AuthConfiguration":
		return tConfig.UserConfig.Auth
	case "MFAConfiguration":
		return tConfig.UserConfig.MFA
	default:
		return nil
	}
}
<|endoftext|>


<commit_before>package main

import (
	"net"
	"net/http"
	"time"
)

type timeoutConn struct {
	socket      net.Conn
	readTimeout time.Duration
}

func (tc *timeoutConn) Read(b []byte) (n int, err error) {
	tc.SetReadDeadline(time.Now().Add(tc.readTimeout))
	return tc.socket.Read(b)
}

func (tc *timeoutConn) Write(b []byte) (n int, err error) {
	tc.SetReadDeadline(time.Now().Add(tc.readTimeout))
	tc.SetWriteDeadline(time.Now().Add(tc.readTimeout))
	defer tc.SetWriteDeadline(time.Time{})
	return tc.socket.Write(b)
}

func (tc *timeoutConn) Close() error {
	return tc.socket.Close()
}

func (tc *timeoutConn) LocalAddr() net.Addr {
	return tc.socket.LocalAddr()
}

func (tc *timeoutConn) RemoteAddr() net.Addr {
	return tc.socket.RemoteAddr()
}

func (tc *timeoutConn) SetDeadline(t time.Time) error {
	return tc.socket.SetDeadline(t)
}

func (tc *timeoutConn) SetReadDeadline(t time.Time) error {
	return tc.socket.SetReadDeadline(t)
}

func (tc *timeoutConn) SetWriteDeadline(t time.Time) error {
	return tc.socket.SetWriteDeadline(t)
}

func TimeoutTransport(timeout time.Duration) *http.Transport {
	dt := timeout
	if dt > time.Minute {
		dt = time.Minute
	}
	return &http.Transport{
		Proxy:             http.ProxyFromEnvironment,
		DisableKeepAlives: true,
		Dial: func(n, addr string) (net.Conn, error) {
			conn, err := net.DialTimeout(n, addr, dt)
			return &timeoutConn{conn, timeout}, err
		},
	}
}
<commit_msg>timeoutConn is a ReaderTo and WriterFrom<commit_after>package main

import (
	"io"
	"net"
	"net/http"
	"time"
)

type timeoutConn struct {
	socket      net.Conn
	readTimeout time.Duration
}

func (tc *timeoutConn) Read(b []byte) (n int, err error) {
	tc.SetReadDeadline(time.Now().Add(tc.readTimeout))
	return tc.socket.Read(b)
}

func (tc *timeoutConn) Write(b []byte) (n int, err error) {
	tc.SetReadDeadline(time.Now().Add(tc.readTimeout))
	tc.SetWriteDeadline(time.Now().Add(tc.readTimeout))
	defer tc.SetWriteDeadline(time.Time{})
	return tc.socket.Write(b)
}

func (tc *timeoutConn) ReadFrom(r io.Reader) (int64, error) {
	return io.Copy(tc.socket, r)
}

func (tc *timeoutConn) WriteTo(w io.Writer) (int64, error) {
	return io.Copy(w, tc.socket)
}

func (tc *timeoutConn) Close() error {
	return tc.socket.Close()
}

func (tc *timeoutConn) LocalAddr() net.Addr {
	return tc.socket.LocalAddr()
}

func (tc *timeoutConn) RemoteAddr() net.Addr {
	return tc.socket.RemoteAddr()
}

func (tc *timeoutConn) SetDeadline(t time.Time) error {
	return tc.socket.SetDeadline(t)
}

func (tc *timeoutConn) SetReadDeadline(t time.Time) error {
	return tc.socket.SetReadDeadline(t)
}

func (tc *timeoutConn) SetWriteDeadline(t time.Time) error {
	return tc.socket.SetWriteDeadline(t)
}

func TimeoutTransport(timeout time.Duration) *http.Transport {
	dt := timeout
	if dt > time.Minute {
		dt = time.Minute
	}
	return &http.Transport{
		Proxy:             http.ProxyFromEnvironment,
		DisableKeepAlives: true,
		Dial: func(n, addr string) (net.Conn, error) {
			conn, err := net.DialTimeout(n, addr, dt)
			return &timeoutConn{conn, timeout}, err
		},
	}
}
<|endoftext|>


<commit_before>package msg

import (
	"bytes"
	"encoding/json"
	"fmt"
	"unicode"

	"github.com/bitfinexcom/bitfinex-api-go/pkg/convert"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/balanceinfo"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/book"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/candle"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/event"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/fundingcredit"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/fundingloan"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/fundingoffer"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/order"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/position"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/status"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/ticker"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/trades"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/wallet"
)

type Msg struct {
	Data     []byte
	Err      error
	CID      int
	IsPublic bool
}

func (m Msg) IsEvent() bool {
	t := bytes.TrimLeftFunc(m.Data, unicode.IsSpace)
	return bytes.HasPrefix(t, []byte("{"))
}

func (m Msg) IsRaw() bool {
	t := bytes.TrimLeftFunc(m.Data, unicode.IsSpace)
	return bytes.HasPrefix(t, []byte("["))
}

func (m Msg) ProcessRaw(chanInfo map[int64]event.Info) (interface{}, error) {
	var raw []interface{}
	if err := json.Unmarshal(m.Data, &raw); err != nil {
		return nil, fmt.Errorf("parsing msg: %s, err: %s", m.Data, err)
	}
	// payload data is always last element of the slice
	pld := raw[len(raw)-1]
	// chanID is always 1st element of the slice
	chID := convert.I64ValOrZero(raw[0])
	// allocate channel name by id to know how to transform raw data
	inf, ok := chanInfo[chID]
	if !ok {
		return nil, fmt.Errorf("unrecognized chanId:%d", chID)
	}

	switch data := pld.(type) {
	case string:
		return event.Info{
			ChanID:    chID,
			Subscribe: event.Subscribe{Event: data},
		}, nil
	case []interface{}:
		switch inf.Channel {
		case "trades":
			return trades.FromWSRaw(inf.Symbol, raw, data)
		case "ticker":
			return ticker.FromWSRaw(inf.Symbol, data)
		case "book":
			return book.FromWSRaw(inf.Symbol, inf.Precision, data)
		case "candles":
			return candle.FromWSRaw(inf.Key, data)
		case "status":
			return status.FromWSRaw(inf.Key, data)
		}
	}

	return raw, nil
}

func (m Msg) ProcessPrivateRaw() (interface{}, error) {
	var raw []interface{}
	if err := json.Unmarshal(m.Data, &raw); err != nil {
		return nil, fmt.Errorf("parsing auth msg: %s, err: %s", m.Data, err)
	}
	// payload data is always last element of the slice
	pld := raw[len(raw)-1]
	// op name is 2nd element
	op := convert.SValOrEmpty(raw[1])

	switch data := pld.(type) {
	case string:
		return event.Info{
			ChanID:    convert.I64ValOrZero(raw[0]),
			Subscribe: event.Subscribe{Event: data},
		}, nil
	case []interface{}:
		switch op {
		case "bu":
			return balanceinfo.UpdateFromRaw(data)
		case "ps":
			return position.SnapshotFromRaw(data)
		case "pn":
			return position.NewFromRaw(data)
		case "pu":
			return position.UpdateFromRaw(data)
		case "pc":
			return position.CancelFromRaw(data)
		case "ws":
			return wallet.SnapshotFromRaw(data)
		case "wu":
			return wallet.UpdateFromRaw(data)
		case "os":
			return order.SnapshotFromRaw(data)
		case "on":
			return order.NewFromRaw(data)
		case "on-req":
			// TODO
		case "ou":
			return order.UpdateFromRaw(data)
		case "oc":
			return order.CancelFromRaw(data)
		case "oc-req":
			// TODO
		case "oc_multi-req":
			// TODO
		case "te":
			return trades.ATEFromRaw(data)
		case "tu":
			return trades.ATEUFromRaw(data)
		case "fte":
			return trades.AFTEFromRaw(data)
		case "ftu":
			return trades.AFTUFromRaw(data)
		case "mis":
			// TODO
		case "miu":
			// TODO
		case "n":
			// TODO
		case "fos":
			return fundingoffer.SnapshotFromRaw(data)
		case "fon":
			return fundingoffer.NewFromRaw(data)
		case "fou":
			return fundingoffer.UpdateFromRaw(data)
		case "foc":
			return fundingoffer.CancelFromRaw(data)
		case "fcs":
			return fundingcredit.SnapshotFromRaw(data)
		case "fcn":
			return fundingcredit.NewFromRaw(data)
		case "fcu":
			return fundingcredit.UpdateFromRaw(data)
		case "fcc":
			return fundingcredit.CancelFromRaw(data)
		case "fls":
			return fundingloan.SnapshotFromRaw(data)
		case "fln":
			return fundingloan.NewFromRaw(data)
		case "flu":
			return fundingloan.UpdateFromRaw(data)
		case "flc":
			return fundingloan.CancelFromRaw(data)
		case "hfts":
			// TODO
		case "uac":
			// TODO
		}
	}

	return raw, nil
}

func (m Msg) ProcessEvent() (i event.Info, err error) {
	if err = json.Unmarshal(m.Data, &i); err != nil {
		return i, fmt.Errorf("parsing msg: %s, err: %s", m.Data, err)
	}
	return
}
<commit_msg>adding support to decode notification type message<commit_after>package msg

import (
	"bytes"
	"encoding/json"
	"fmt"
	"unicode"

	"github.com/bitfinexcom/bitfinex-api-go/pkg/convert"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/balanceinfo"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/book"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/candle"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/event"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/fundingcredit"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/fundingloan"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/fundingoffer"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/notification"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/order"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/position"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/status"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/ticker"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/trades"
	"github.com/bitfinexcom/bitfinex-api-go/pkg/models/wallet"
)

type Msg struct {
	Data     []byte
	Err      error
	CID      int
	IsPublic bool
}

func (m Msg) IsEvent() bool {
	t := bytes.TrimLeftFunc(m.Data, unicode.IsSpace)
	return bytes.HasPrefix(t, []byte("{"))
}

func (m Msg) IsRaw() bool {
	t := bytes.TrimLeftFunc(m.Data, unicode.IsSpace)
	return bytes.HasPrefix(t, []byte("["))
}

func (m Msg) ProcessRaw(chanInfo map[int64]event.Info) (interface{}, error) {
	var raw []interface{}
	if err := json.Unmarshal(m.Data, &raw); err != nil {
		return nil, fmt.Errorf("parsing msg: %s, err: %s", m.Data, err)
	}
	// payload data is always last element of the slice
	pld := raw[len(raw)-1]
	// chanID is always 1st element of the slice
	chID := convert.I64ValOrZero(raw[0])
	// allocate channel name by id to know how to transform raw data
	inf, ok := chanInfo[chID]
	if !ok {
		return nil, fmt.Errorf("unrecognized chanId:%d", chID)
	}

	switch data := pld.(type) {
	case string:
		return event.Info{
			ChanID:    chID,
			Subscribe: event.Subscribe{Event: data},
		}, nil
	case []interface{}:
		switch inf.Channel {
		case "trades":
			return trades.FromWSRaw(inf.Symbol, raw, data)
		case "ticker":
			return ticker.FromWSRaw(inf.Symbol, data)
		case "book":
			return book.FromWSRaw(inf.Symbol, inf.Precision, data)
		case "candles":
			return candle.FromWSRaw(inf.Key, data)
		case "status":
			return status.FromWSRaw(inf.Key, data)
		}
	}

	return raw, nil
}

func (m Msg) ProcessPrivateRaw() (interface{}, error) {
	var raw []interface{}
	if err := json.Unmarshal(m.Data, &raw); err != nil {
		return nil, fmt.Errorf("parsing auth msg: %s, err: %s", m.Data, err)
	}
	// payload data is always last element of the slice
	pld := raw[len(raw)-1]
	// op name is 2nd element
	op := convert.SValOrEmpty(raw[1])

	switch data := pld.(type) {
	case string:
		return event.Info{
			ChanID:    convert.I64ValOrZero(raw[0]),
			Subscribe: event.Subscribe{Event: data},
		}, nil
	case []interface{}:
		switch op {
		case "bu":
			return balanceinfo.UpdateFromRaw(data)
		case "ps":
			return position.SnapshotFromRaw(data)
		case "pn":
			return position.NewFromRaw(data)
		case "pu":
			return position.UpdateFromRaw(data)
		case "pc":
			return position.CancelFromRaw(data)
		case "ws":
			return wallet.SnapshotFromRaw(data)
		case "wu":
			return wallet.UpdateFromRaw(data)
		case "os":
			return order.SnapshotFromRaw(data)
		case "on":
			return order.NewFromRaw(data)
		case "ou":
			return order.UpdateFromRaw(data)
		case "oc":
			return order.CancelFromRaw(data)
		case "te":
			return trades.ATEFromRaw(data)
		case "tu":
			return trades.ATEUFromRaw(data)
		case "fte":
			return trades.AFTEFromRaw(data)
		case "ftu":
			return trades.AFTUFromRaw(data)
		case "mis":
			// TODO
		case "miu":
			// TODO
		case "n":
			return notification.FromRaw(data)
		case "fos":
			return fundingoffer.SnapshotFromRaw(data)
		case "fon":
			return fundingoffer.NewFromRaw(data)
		case "fou":
			return fundingoffer.UpdateFromRaw(data)
		case "foc":
			return fundingoffer.CancelFromRaw(data)
		case "fcs":
			return fundingcredit.SnapshotFromRaw(data)
		case "fcn":
			return fundingcredit.NewFromRaw(data)
		case "fcu":
			return fundingcredit.UpdateFromRaw(data)
		case "fcc":
			return fundingcredit.CancelFromRaw(data)
		case "fls":
			return fundingloan.SnapshotFromRaw(data)
		case "fln":
			return fundingloan.NewFromRaw(data)
		case "flu":
			return fundingloan.UpdateFromRaw(data)
		case "flc":
			return fundingloan.CancelFromRaw(data)
		case "hfts":
			// TODO
		case "uac":
			// TODO
		}
	}

	return raw, nil
}

func (m Msg) ProcessEvent() (i event.Info, err error) {
	if err = json.Unmarshal(m.Data, &i); err != nil {
		return i, fmt.Errorf("parsing msg: %s, err: %s", m.Data, err)
	}
	return
}
<|endoftext|>


<commit_before>// Copyright 2018 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package policy

import (
	"net"

	"github.com/cilium/cilium/pkg/policy/api"
)

// getPrefixesFromCIDR fetches all CIDRs referred to by the specified slice
// and returns them as regular golang CIDR objects.
func getPrefixesFromCIDR(cidrs api.CIDRSlice) []*net.IPNet {
	res := make([]*net.IPNet, 0, len(cidrs))
	for _, cidr := range cidrs {
		_, prefix, err := net.ParseCIDR(string(cidr))
		if err != nil {
			// Likely the CIDR is specified in host format.
			ip := net.ParseIP(string(cidr))
			if ip != nil {
				bits := net.IPv6len * 8
				if ip.To4() != nil {
					ip = ip.To4()
					bits = net.IPv4len * 8
				}
				prefix = &net.IPNet{ip, net.CIDRMask(bits, bits)}
			}
		}
		if prefix != nil {
			res = append(res, prefix)
		}
	}
	return res
}

// getPrefixesFromCIDRSet fetches all CIDRs referred to by the specified slice
// and returns them as regular golang CIDR objects.
func getPrefixesFromCIDRSet(rules api.CIDRRuleSlice) []*net.IPNet {
	cidrs := api.ComputeResultantCIDRSet(rules)
	return getPrefixesFromCIDR(cidrs)
}

// GetCIDRPrefixes runs through the specified 'rules' to find every reference
// to a CIDR in the rules, and returns a slice containing all of these CIDRs.
// Multiple rules referring to the same CIDR will result in multiple copies of
// the CIDR in the returned slice.
//
// Assumes that validation already occurred on 'rules'.
func GetCIDRPrefixes(rules api.Rules) []*net.IPNet {
	if len(rules) == 0 {
		return nil
	}
	res := make([]*net.IPNet, 0, 32)
	for _, r := range rules {
		for _, ir := range r.Ingress {
			if len(ir.FromCIDR) > 0 {
				res = append(res, getPrefixesFromCIDR(ir.FromCIDR)...)
			}
			if len(ir.FromCIDRSet) > 0 {
				res = append(res, getPrefixesFromCIDRSet(ir.FromCIDRSet)...)
			}
		}
		for _, er := range r.Egress {
			if len(er.ToCIDR) > 0 {
				res = append(res, getPrefixesFromCIDR(er.ToCIDR)...)
			}
			if len(er.ToCIDRSet) > 0 {
				res = append(res, getPrefixesFromCIDRSet(er.ToCIDRSet)...)
			}
		}
	}
	return res
}
<commit_msg>pkg/policy: fix go vet issues<commit_after>// Copyright 2018 Authors of Cilium
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package policy

import (
	"net"

	"github.com/cilium/cilium/pkg/policy/api"
)

// getPrefixesFromCIDR fetches all CIDRs referred to by the specified slice
// and returns them as regular golang CIDR objects.
func getPrefixesFromCIDR(cidrs api.CIDRSlice) []*net.IPNet {
	res := make([]*net.IPNet, 0, len(cidrs))
	for _, cidr := range cidrs {
		_, prefix, err := net.ParseCIDR(string(cidr))
		if err != nil {
			// Likely the CIDR is specified in host format.
			ip := net.ParseIP(string(cidr))
			if ip != nil {
				bits := net.IPv6len * 8
				if ip.To4() != nil {
					ip = ip.To4()
					bits = net.IPv4len * 8
				}
				prefix = &net.IPNet{
					IP:   ip,
					Mask: net.CIDRMask(bits, bits),
				}
			}
		}
		if prefix != nil {
			res = append(res, prefix)
		}
	}
	return res
}

// getPrefixesFromCIDRSet fetches all CIDRs referred to by the specified slice
// and returns them as regular golang CIDR objects.
func getPrefixesFromCIDRSet(rules api.CIDRRuleSlice) []*net.IPNet {
	cidrs := api.ComputeResultantCIDRSet(rules)
	return getPrefixesFromCIDR(cidrs)
}

// GetCIDRPrefixes runs through the specified 'rules' to find every reference
// to a CIDR in the rules, and returns a slice containing all of these CIDRs.
// Multiple rules referring to the same CIDR will result in multiple copies of
// the CIDR in the returned slice.
//
// Assumes that validation already occurred on 'rules'.
func GetCIDRPrefixes(rules api.Rules) []*net.IPNet {
	if len(rules) == 0 {
		return nil
	}
	res := make([]*net.IPNet, 0, 32)
	for _, r := range rules {
		for _, ir := range r.Ingress {
			if len(ir.FromCIDR) > 0 {
				res = append(res, getPrefixesFromCIDR(ir.FromCIDR)...)
			}
			if len(ir.FromCIDRSet) > 0 {
				res = append(res, getPrefixesFromCIDRSet(ir.FromCIDRSet)...)
			}
		}
		for _, er := range r.Egress {
			if len(er.ToCIDR) > 0 {
				res = append(res, getPrefixesFromCIDR(er.ToCIDR)...)
			}
			if len(er.ToCIDRSet) > 0 {
				res = append(res, getPrefixesFromCIDRSet(er.ToCIDRSet)...)
			}
		}
	}
	return res
}
<|endoftext|>


<commit_before>package plugins

import (
	"bytes"
	"fmt"

	"os"

	"github.com/BurntSushi/toml"
	log "github.com/Sirupsen/logrus"
	"github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/strslice"
	"github.com/maliceio/malice/config"
	er "github.com/maliceio/malice/malice/errors"
	"github.com/maliceio/malice/malice/maldocker"
	"github.com/parnurzeal/gorequest"
)

// StartPlugin starts plugin
func (plugin Plugin) StartPlugin(client *maldocker.Docker, sample string, logs bool) (types.ContainerJSONBase, error) {
	contJSON, err := client.StartContainer(strslice.New("-t", sample), plugin.Name, plugin.Image, logs)
	er.CheckError(err)

	return contJSON, err
}

// RunIntelPlugins run all Intel plugins
func RunIntelPlugins(client *maldocker.Docker, hash string, logs bool) {
	var cont types.ContainerJSONBase
	var err error
	for _, plugin := range GetIntelPlugins(true) {
		if plugin.Cmd != "" {
			cont, err = client.StartContainer(strslice.New("-t", plugin.Cmd, hash), plugin.Name, plugin.Image, logs)
			er.CheckError(err)
		} else {
			cont, err = client.StartContainer(strslice.New("-t", hash), plugin.Name, plugin.Image, logs)
			er.CheckError(err)
		}
		log.WithFields(log.Fields{
			"id": cont.ID,
			"ip": client.GetIP(),
			// "url":      "http://" + maldocker.GetIP(),
			"name": cont.Name,
			"env":  config.Conf.Environment.Run,
		}).Debug("Plugin Container Started")

		err := client.RemoveContainer(cont, false, false, false)
		er.CheckError(err)
	}
}

func printStatus(resp gorequest.Response, body string, errs []error) {
	fmt.Println(resp.Status)
}

// PostResults post plugin results to Malice Webhook
func PostResults(url string, resultJSON []byte, taskID string) {
	request := gorequest.New()
	if config.Conf.Proxy.Enable {
		request = gorequest.New().Proxy(config.Conf.Proxy.HTTP)
	}
	request.Post(url).
		Set("Task", taskID).
		Send(resultJSON).
		End(printStatus)
}

//InstallPlugin installs a new malice plugin
func InstallPlugin(plugin *Plugin) (err error) {

	var newPlugin = Configuration{
		[]Plugin{
			Plugin{
				Name:        plugin.Name,
				Enabled:     plugin.Enabled,
				Category:    plugin.Category,
				Description: plugin.Description,
				Image:       plugin.Image,
				Mime:        plugin.Mime,
			},
		},
	}

	buf := new(bytes.Buffer)
	er.CheckError(toml.NewEncoder(buf).Encode(newPlugin))
	fmt.Println(buf.String())
	// open plugin config file
	f, err := os.OpenFile("./plugins.toml", os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	// write new plugin to installed plugin config
	if _, err = f.WriteString("\n" + buf.String()); err != nil {
		panic(err)
	}
	return
}

// InstalledPluginsCheck checks that all enabled plugins are installed
func InstalledPluginsCheck(client *maldocker.Docker) bool {
	for _, plugin := range getEnabled(Plugs.Plugins) {
		if _, exists, _ := client.ImageExists(plugin.Image); !exists {
			return false
		}
	}
	return true
}

// UpdatePlugin performs a docker pull on all registered plugins checking for updates
func (plugin Plugin) UpdatePlugin(client *maldocker.Docker) {
	client.PullImage(plugin.Image, "latest")
}

// UpdateAllPlugins performs a docker pull on all registered plugins checking for updates
func UpdateAllPlugins(client *maldocker.Docker) {
	plugins := Plugs.Plugins
	for _, plugin := range plugins {
		client.PullImage(plugin.Image, "latest")
	}
}
<commit_msg>update plugin update all output<commit_after>package plugins

import (
	"bytes"
	"fmt"

	"os"

	"github.com/BurntSushi/toml"
	log "github.com/Sirupsen/logrus"
	"github.com/docker/engine-api/types"
	"github.com/docker/engine-api/types/strslice"
	"github.com/maliceio/malice/config"
	er "github.com/maliceio/malice/malice/errors"
	"github.com/maliceio/malice/malice/maldocker"
	"github.com/parnurzeal/gorequest"
)

// StartPlugin starts plugin
func (plugin Plugin) StartPlugin(client *maldocker.Docker, sample string, logs bool) (types.ContainerJSONBase, error) {
	contJSON, err := client.StartContainer(strslice.New("-t", sample), plugin.Name, plugin.Image, logs)
	er.CheckError(err)

	return contJSON, err
}

// RunIntelPlugins run all Intel plugins
func RunIntelPlugins(client *maldocker.Docker, hash string, logs bool) {
	var cont types.ContainerJSONBase
	var err error
	for _, plugin := range GetIntelPlugins(true) {
		if plugin.Cmd != "" {
			cont, err = client.StartContainer(strslice.New("-t", plugin.Cmd, hash), plugin.Name, plugin.Image, logs)
			er.CheckError(err)
		} else {
			cont, err = client.StartContainer(strslice.New("-t", hash), plugin.Name, plugin.Image, logs)
			er.CheckError(err)
		}
		log.WithFields(log.Fields{
			"id": cont.ID,
			"ip": client.GetIP(),
			// "url":      "http://" + maldocker.GetIP(),
			"name": cont.Name,
			"env":  config.Conf.Environment.Run,
		}).Debug("Plugin Container Started")

		err := client.RemoveContainer(cont, false, false, false)
		er.CheckError(err)
	}
}

func printStatus(resp gorequest.Response, body string, errs []error) {
	fmt.Println(resp.Status)
}

// PostResults post plugin results to Malice Webhook
func PostResults(url string, resultJSON []byte, taskID string) {
	request := gorequest.New()
	if config.Conf.Proxy.Enable {
		request = gorequest.New().Proxy(config.Conf.Proxy.HTTP)
	}
	request.Post(url).
		Set("Task", taskID).
		Send(resultJSON).
		End(printStatus)
}

//InstallPlugin installs a new malice plugin
func InstallPlugin(plugin *Plugin) (err error) {

	var newPlugin = Configuration{
		[]Plugin{
			Plugin{
				Name:        plugin.Name,
				Enabled:     plugin.Enabled,
				Category:    plugin.Category,
				Description: plugin.Description,
				Image:       plugin.Image,
				Mime:        plugin.Mime,
			},
		},
	}

	buf := new(bytes.Buffer)
	er.CheckError(toml.NewEncoder(buf).Encode(newPlugin))
	fmt.Println(buf.String())
	// open plugin config file
	f, err := os.OpenFile("./plugins.toml", os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	// write new plugin to installed plugin config
	if _, err = f.WriteString("\n" + buf.String()); err != nil {
		panic(err)
	}
	return
}

// InstalledPluginsCheck checks that all enabled plugins are installed
func InstalledPluginsCheck(client *maldocker.Docker) bool {
	for _, plugin := range getEnabled(Plugs.Plugins) {
		if _, exists, _ := client.ImageExists(plugin.Image); !exists {
			return false
		}
	}
	return true
}

// UpdatePlugin performs a docker pull on all registered plugins checking for updates
func (plugin Plugin) UpdatePlugin(client *maldocker.Docker) {
	client.PullImage(plugin.Image, "latest")
}

// UpdateAllPlugins performs a docker pull on all registered plugins checking for updates
func UpdateAllPlugins(client *maldocker.Docker) {
	plugins := Plugs.Plugins
	for _, plugin := range plugins {
		fmt.Println("[Updating Plugin] ===> ", plugin.Name)
		client.PullImage(plugin.Image, "latest")
	}
}
<|endoftext|>


<commit_before>// This file is subject to a 1-clause BSD license.
// Its contents can be found in the enclosed LICENSE file.

package url

import (
	"bytes"
	"github.com/jteeuwen/ini"
	"github.com/jteeuwen/ircb/plugin"
	"github.com/jteeuwen/ircb/proto"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
)

var (
	// Each entry holds a regex pattern which should be excluded
	// from the url-title-lookup.
	exclude []*regexp.Regexp

	// Patern which recognizes urls.
	url = regexp.MustCompile(`\bhttps?\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]+(\:[0-9]+)?(/\S*)?\b`)
)

// Init initializes the plugin. it loads configuration data and binds
// commands and protocol handlers.
func Init(profile string, c *proto.Client) {
	log.Println("Initializing: url")

	ini := ini.New()
	err := ini.Load(plugin.ConfigPath(profile, "url"))

	if err != nil {
		log.Fatal(err)
	}

	s := ini.Section("exclude")
	list := s.List("url")
	exclude = make([]*regexp.Regexp, len(list))

	for i := range list {
		exclude[i], err = regexp.Compile(list[i])
		if err != nil {
			log.Fatalf("- Invalid pattern: %s", list[i])
		}
	}

	c.Bind(proto.CmdPrivMsg, parseURL)
}

// parseURL looks for URL's embedded in incoming messages.
// If they are valid http[s] url's and not in the exclude list,
// we use them to fetch page titles from the internet.
func parseURL(c *proto.Client, m *proto.Message) {
	list := url.FindAllString(m.Data, -1)
	if len(list) == 0 {
		return
	}

	for _, url := range list {
		if !excluded(url) {
			go fetchTitle(c, m, url)
		}
	}
}

// excluded returns true if the given url is part of the exclusion list.
func excluded(url string) bool {
	for _, excl := range exclude {
		if excl.MatchString(url) {
			return true
		}
	}

	return false
}

// fetchTitle attempts to retrieve the title element for a given url.
func fetchTitle(c *proto.Client, m *proto.Message, url string) {
	resp, err := http.Get(url)
	if err != nil {
		log.Printf("[url] Failed to fetch %s", url)
		return
	}

	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	if err != nil {
		log.Printf("[url] Failed to read %s", url)
		return
	}

	body = bytes.ToLower(body)
	s := bytes.Index(body, []byte("<title>"))
	if s == -1 {
		return
	}

	body = body[s+7:]

	e := bytes.Index(body, []byte("</title>"))
	if e == -1 {
		e = len(body) - 1
	}

	body = bytes.TrimSpace(body[:e])

	c.PrivMsg(m.Receiver, "%s's link shows: %s", m.SenderName, body)
}
<commit_msg>Ensures the url plugin unescapes HTML entities in page titles.<commit_after>// This file is subject to a 1-clause BSD license.
// Its contents can be found in the enclosed LICENSE file.

package url

import (
	"bytes"
	"github.com/jteeuwen/ini"
	"github.com/jteeuwen/ircb/plugin"
	"github.com/jteeuwen/ircb/proto"
	"html"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
)

var (
	// Each entry holds a regex pattern which should be excluded
	// from the url-title-lookup.
	exclude []*regexp.Regexp

	// Patern which recognizes urls.
	url = regexp.MustCompile(`\bhttps?\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]+(\:[0-9]+)?(/\S*)?\b`)
)

// Init initializes the plugin. it loads configuration data and binds
// commands and protocol handlers.
func Init(profile string, c *proto.Client) {
	log.Println("Initializing: url")

	ini := ini.New()
	err := ini.Load(plugin.ConfigPath(profile, "url"))

	if err != nil {
		log.Fatal(err)
	}

	s := ini.Section("exclude")
	list := s.List("url")
	exclude = make([]*regexp.Regexp, len(list))

	for i := range list {
		exclude[i], err = regexp.Compile(list[i])
		if err != nil {
			log.Fatalf("- Invalid pattern: %s", list[i])
		}
	}

	c.Bind(proto.CmdPrivMsg, parseURL)
}

// parseURL looks for URL's embedded in incoming messages.
// If they are valid http[s] url's and not in the exclude list,
// we use them to fetch page titles from the internet.
func parseURL(c *proto.Client, m *proto.Message) {
	list := url.FindAllString(m.Data, -1)
	if len(list) == 0 {
		return
	}

	for _, url := range list {
		if !excluded(url) {
			go fetchTitle(c, m, url)
		}
	}
}

// excluded returns true if the given url is part of the exclusion list.
func excluded(url string) bool {
	for _, excl := range exclude {
		if excl.MatchString(url) {
			return true
		}
	}

	return false
}

// fetchTitle attempts to retrieve the title element for a given url.
func fetchTitle(c *proto.Client, m *proto.Message, url string) {
	resp, err := http.Get(url)
	if err != nil {
		log.Printf("[url] Failed to fetch %s", url)
		return
	}

	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()

	if err != nil {
		log.Printf("[url] Failed to read %s", url)
		return
	}

	body = bytes.ToLower(body)
	s := bytes.Index(body, []byte("<title>"))
	if s == -1 {
		return
	}

	body = body[s+7:]

	e := bytes.Index(body, []byte("</title>"))
	if e == -1 {
		e = len(body) - 1
	}

	body = bytes.TrimSpace(body[:e])

	c.PrivMsg(m.Receiver, "%s's link shows: %s",
		m.SenderName, html.UnescapeString(string(body)))
}
<|endoftext|>


<commit_before>package plx

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha512"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

const POLONIEX_TRADING_API_URL = "https://poloniex.com/tradingApi"
const API_CREDENTIALS_FILE = "./.creds.json"

type CompleteBalance struct {
	Currency  string
	Available float64 `json:"available"`
	OnOrders  float64 `json:"onOrders"`
	BtcValue  float64 `json:"btcValue"`
}

func CompleteBalances() ([]CompleteBalance, error) {
	balances := make([]CompleteBalance, 0)
	client := NewTradingApiClient()

	values := &url.Values{}
	values.Set("command", "returnCompleteBalances")

	resp, err := client.Post(values)

	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("request failed: %s\n\n", resp.Status, bytes.NewBuffer(body).String())
	}

	respData := make(map[string]map[string]string)

	err = json.Unmarshal(body, &respData)

	for key, data := range respData {
		balance := CompleteBalance{}
		balance.Currency = key
		balance.Available, _ = strconv.ParseFloat(data["available"], 64)
		balance.OnOrders, _ = strconv.ParseFloat(data["onOrders"], 64)
		balance.BtcValue, _ = strconv.ParseFloat(data["btcValue"], 64)
		balances = append(balances, balance)
	}

	return balances, nil
}

// {"orderNumber":"120466","type":"sell","rate":"0.025","amount":"100","total":"2.5"}
type OpenOrder struct {
	Number int64 `json:"orderNumber,string"`
	Type   string
	Rate   float64 `json:",string"`
	Amount float64 `json:",string"`
	Total  float64 `json:",string"`
}

func AllOpenOrders() (marketOrders map[string][]OpenOrder, err error) {
	marketOrders = make(map[string][]OpenOrder)
	client := NewTradingApiClient()

	values := &url.Values{}
	values.Set("command", "returnOpenOrders")
	values.Set("currencyPair", "all")

	resp, err := client.Post(values)

	if err != nil {
		return marketOrders, err
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	if resp.StatusCode != 200 {
		return marketOrders, fmt.Errorf("request failed: %s\n\n", resp.Status, bytes.NewBuffer(body).String())
	}

	err = json.Unmarshal(body, &marketOrders)

	return marketOrders, err
}

type TradingApiClient struct {
	*http.Client
}

func NewTradingApiClient() *TradingApiClient {
	client := &http.Client{}
	return &TradingApiClient{client}
}

func (client *TradingApiClient) Post(formData *url.Values) (*http.Response, error) {
	apiKey, apiSecret, err := client.ReadTradingApiCredentials()

	if err != nil {
		return nil, err
	}

	reqBody, signature := client.SignFormData(apiSecret, formData)

	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", POLONIEX_TRADING_API_URL, bytes.NewBufferString(reqBody))

	if err != nil {
		return nil, err
	}

	req.Header.Set("Key", apiKey)
	req.Header.Set("Sign", signature)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Accept", "application/json")

	return client.Do(req)
}

func (client *TradingApiClient) SignFormData(apiSecret string, formData *url.Values) (reqBody, signature string) {
	nonce := time.Now().UnixNano()
	formData.Set("nonce", strconv.FormatInt(nonce, 10))
	reqBody = formData.Encode()

	mac := hmac.New(sha512.New, []byte(apiSecret))
	mac.Write([]byte(reqBody))
	sigBytes := mac.Sum(nil)
	sigEncoded := hex.EncodeToString(sigBytes)

	return reqBody, sigEncoded
}

func (client *TradingApiClient) ReadTradingApiCredentials() (key, secret string, err error) {
	creds := make(map[string]string)

	fileContent, err := ioutil.ReadFile(API_CREDENTIALS_FILE)
	if err != nil {
		return key, secret, err
	}

	err = json.Unmarshal(fileContent, &creds)
	if err != nil {
		return key, secret, err
	}

	return creds["key"], creds["secret"], nil
}
<commit_msg>no comment<commit_after>package plx

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha512"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

const POLONIEX_TRADING_API_URL = "https://poloniex.com/tradingApi"
const API_CREDENTIALS_FILE = "./.creds.json"

type CompleteBalance struct {
	Currency  string
	Available float64 `json:"available"`
	OnOrders  float64 `json:"onOrders"`
	BtcValue  float64 `json:"btcValue"`
}

func CompleteBalances() ([]CompleteBalance, error) {
	balances := make([]CompleteBalance, 0)
	client := NewTradingApiClient()

	values := &url.Values{}
	values.Set("command", "returnCompleteBalances")

	resp, err := client.Post(values)

	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("request failed: %s\n\n", resp.Status, bytes.NewBuffer(body).String())
	}

	respData := make(map[string]map[string]string)

	err = json.Unmarshal(body, &respData)

	for key, data := range respData {
		balance := CompleteBalance{}
		balance.Currency = key
		balance.Available, _ = strconv.ParseFloat(data["available"], 64)
		balance.OnOrders, _ = strconv.ParseFloat(data["onOrders"], 64)
		balance.BtcValue, _ = strconv.ParseFloat(data["btcValue"], 64)
		balances = append(balances, balance)
	}

	return balances, nil
}

type OpenOrder struct {
	Number int64 `json:"orderNumber,string"`
	Type   string
	Rate   float64 `json:",string"`
	Amount float64 `json:",string"`
	Total  float64 `json:",string"`
}

func AllOpenOrders() (marketOrders map[string][]OpenOrder, err error) {
	marketOrders = make(map[string][]OpenOrder)
	client := NewTradingApiClient()

	values := &url.Values{}
	values.Set("command", "returnOpenOrders")
	values.Set("currencyPair", "all")

	resp, err := client.Post(values)

	if err != nil {
		return marketOrders, err
	}

	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	if resp.StatusCode != 200 {
		return marketOrders, fmt.Errorf("request failed: %s\n\n", resp.Status, bytes.NewBuffer(body).String())
	}

	err = json.Unmarshal(body, &marketOrders)

	return marketOrders, err
}

type TradingApiClient struct {
	*http.Client
}

func NewTradingApiClient() *TradingApiClient {
	client := &http.Client{}
	return &TradingApiClient{client}
}

func (client *TradingApiClient) Post(formData *url.Values) (*http.Response, error) {
	apiKey, apiSecret, err := client.ReadTradingApiCredentials()

	if err != nil {
		return nil, err
	}

	reqBody, signature := client.SignFormData(apiSecret, formData)

	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", POLONIEX_TRADING_API_URL, bytes.NewBufferString(reqBody))

	if err != nil {
		return nil, err
	}

	req.Header.Set("Key", apiKey)
	req.Header.Set("Sign", signature)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Accept", "application/json")

	return client.Do(req)
}

func (client *TradingApiClient) SignFormData(apiSecret string, formData *url.Values) (reqBody, signature string) {
	nonce := time.Now().UnixNano()
	formData.Set("nonce", strconv.FormatInt(nonce, 10))
	reqBody = formData.Encode()

	mac := hmac.New(sha512.New, []byte(apiSecret))
	mac.Write([]byte(reqBody))
	sigBytes := mac.Sum(nil)
	sigEncoded := hex.EncodeToString(sigBytes)

	return reqBody, sigEncoded
}

func (client *TradingApiClient) ReadTradingApiCredentials() (key, secret string, err error) {
	creds := make(map[string]string)

	fileContent, err := ioutil.ReadFile(API_CREDENTIALS_FILE)
	if err != nil {
		return key, secret, err
	}

	err = json.Unmarshal(fileContent, &creds)
	if err != nil {
		return key, secret, err
	}

	return creds["key"], creds["secret"], nil
}
<|endoftext|>


<commit_before>package ui

import (
	"bytes"
	"fmt"
	"log"
	"sort"
	"strings"
	"time"

	"github.com/lhz/sidpicker/csdb"
	"github.com/lhz/sidpicker/hvsc"
	"github.com/lhz/sidpicker/player"
	"github.com/nsf/termbox-go"
)

const (
	MODE_BROWSE = iota
	MODE_SEARCH
)

var w, h int
var list *List
var mode int
var debugInfo string
var searchTerm []rune
var searchCursorPos int
var quit = false

func Setup(initialSearch string) {
	err := termbox.Init()
	if err != nil {
		log.Panicln(err)
	}

	w, h = termbox.Size()

	if len(initialSearch) > 0 {
		searchTerm = []rune(initialSearch)
		hvsc.Filter(string(searchTerm))
	}

	list = NewList(h - 2)

	termbox.SetInputMode(termbox.InputEsc | termbox.InputMouse)
	draw()
}

func Run() {
	defer termbox.Close()

	mode = MODE_BROWSE

	tickChan := time.NewTicker(1 * time.Second).C

	eventChan := make(chan termbox.Event)
	go func() {
		for {
			eventChan <- termbox.PollEvent()
		}
	}()

	for !quit {
		debugInfo = ""
		select {
		case ev := <-eventChan:
			switch ev.Type {
			case termbox.EventKey:
				keyEvent(ev)
				draw()
			case termbox.EventMouse:
				mouseEvent(ev)
				draw()
			case termbox.EventResize:
				resizeEvent(ev)
				draw()
			case termbox.EventError:
				panic(ev.Err)
			}
		case <-tickChan:
			if player.Playing {
				draw()
			}
		}
	}
}

func resizeEvent(ev termbox.Event) {
	w, h = ev.Width, ev.Height
	draw()
}

func keyEvent(ev termbox.Event) {
	if mode == MODE_SEARCH {
		keyEventSearch(ev)
		return
	}
	switch ev.Key {
	case termbox.KeyCtrlC, termbox.KeyEsc:
		if player.Playing {
			player.Stop()
		} else {
			quit = true
		}
	case termbox.KeyPgup:
		list.PrevPage()
	case termbox.KeyPgdn:
		list.NextPage()
	case termbox.KeyArrowUp:
		list.PrevTune()
	case termbox.KeyArrowDown:
		list.NextTune()
	case termbox.KeyArrowLeft:
		player.PrevSong()
	case termbox.KeyArrowRight:
		player.NextSong()
	case termbox.KeyEnter:
		player.Play(list.CurrentItem().TuneIndex, -1)
		sort.Sort(csdb.ByDate(player.CurrentTune.Releases))
	case termbox.KeySpace:
		list.NextTune()
		player.Play(list.CurrentItem().TuneIndex, -1)
		sort.Sort(csdb.ByDate(player.CurrentTune.Releases))
	case termbox.KeyDelete:
		player.Stop()
	case 0:
		if n := strings.IndexRune("0123456789", ev.Ch); n > 0 {
			if player.Playing && n <= player.CurrentTune.Header.Songs {
				player.PlaySub(n)
			}
			return
		}
		if ev.Ch == '/' {
			mode = MODE_SEARCH
		}
	default:
		debugInfo = string(ev.Key)
	}
}

func keyEventSearch(ev termbox.Event) {
	switch ev.Key {
	case termbox.KeyCtrlC, termbox.KeyEsc:
		mode = MODE_BROWSE
	case termbox.KeyArrowLeft:
		if searchCursorPos > 0 {
			searchCursorPos--
		}
	case termbox.KeyArrowRight:
		if searchCursorPos < len(searchTerm) {
			searchCursorPos++
		}
	case termbox.KeyEnter:
		if hvsc.Filter(string(searchTerm)) {
			list = NewList(h - 2)
			mode = MODE_BROWSE
		}
	case termbox.KeySpace:
		searchInsert(rune(' '))
	case 0:
		searchInsert(ev.Ch)
	case 0x7F:
		if searchCursorPos > 0 {
			searchTerm = append(searchTerm[0:searchCursorPos-1], searchTerm[searchCursorPos:len(searchTerm)]...)
			searchCursorPos--
		}
	default:
		debugInfo = string(ev.Key)
	}
}

func mouseEvent(ev termbox.Event) {
	x := ev.MouseX
	y := ev.MouseY
	if x < 38 && y > 0 && y < h - 1 {
		if list.TuneAtPos(y - 1) {
			player.Play(list.CurrentItem().TuneIndex, -1)
			sort.Sort(csdb.ByDate(player.CurrentTune.Releases))
		}
	}
}

func searchInsert(ch rune) {
	searchTerm = append(searchTerm, rune(' '))
	copy(searchTerm[searchCursorPos+1:], searchTerm[searchCursorPos:])
	searchTerm[searchCursorPos] = ch
	searchCursorPos++
}

func draw() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	drawHeader()
	drawList()
	drawTuneInfo()
	drawReleases()
	drawFooter()
	termbox.Flush()
}

func drawHeader() {
	var header string
	bg := termbox.ColorBlack
	switch mode {
	case MODE_BROWSE:
		header = fmt.Sprintf("Search: %s", string(searchTerm))
		termbox.HideCursor()
	case MODE_SEARCH:
		header = fmt.Sprintf("Search: %s", string(searchTerm))
		bg = termbox.ColorMagenta
		termbox.SetCursor(8+searchCursorPos, 0)
	}
	header = fmt.Sprintf(fmt.Sprintf("%%s%%%ds", w-len([]rune(header))), header, "")
	writeAt(0, 0, header, termbox.ColorWhite|termbox.AttrBold, bg)
}

func drawFooter() {
	footer := fmt.Sprintf("%d/%d  %s", list.CurrentItem().TuneIndex+1, hvsc.NumFilteredTunes, debugInfo)
	footer = fmt.Sprintf(fmt.Sprintf("%%s%%%ds", w-len([]rune(footer))), footer, "")
	writeAt(0, h-1, footer, termbox.ColorWhite, termbox.ColorBlack)
}

func drawTuneInfo() {
	if !player.Playing {
		return
	}
	tune := player.CurrentTune
	ox := 42
	oy := 2
	fg := termbox.ColorDefault
	bg := termbox.ColorDefault

	writeAt(ox, oy+0, fmt.Sprintf("Title:    %s", tune.Title()), fg, bg)
	writeAt(ox, oy+1, fmt.Sprintf("Author:   %s", tune.Header.Author), fg, bg)
	writeAt(ox, oy+2, fmt.Sprintf("Released: %s", tune.Header.Released), fg, bg)

	writeAt(ox, oy+4, fmt.Sprintf("Tune: %d/%d  Length: %s  Time: %s",
		player.CurrentSong, tune.Header.Songs, player.SongLength(), player.Elapsed()), fg, bg)

	if len(tune.Info) == 0 {
		return
	}

	writeAt(ox, oy+6, "STIL Information:", termbox.ColorYellow|termbox.AttrBold, termbox.ColorBlack)

	for i, line := range tune.Info {
		if oy+8+i > h-2 {
			break
		}
		writeAt(ox, oy+8+i, line, fg, bg)
	}
}

func drawReleases() {
	if !player.Playing {
		return
	}
	tune := player.CurrentTune
	if len(tune.Releases) == 0 {
		return
	}

	ox := 42
	oy := 8
	mx := 0
	if len(tune.Info) > 0 {
		oy = oy + 3 + len(tune.Info)
	}

	//fg := termbox.ColorDefault
	bg := termbox.ColorDefault

	line := fmt.Sprintf("Known Releases: %d", len(tune.Releases))
	writeAt(ox, oy, line, termbox.ColorYellow|termbox.AttrBold, termbox.ColorBlack)

	oy += 2
	y := oy

	for _, r := range tune.Releases {

		credits := make([]string, 0)
		if r.Date != "" {
			credits = append(credits, r.Date)
		}
		if len(r.Groups) > 0 {
			credits = append(credits, strings.Join(r.Groups, ", "))
		}

		bylines := lineSplit(strings.Join(credits, " by "), 36)
		if y+len(bylines)+1 > h-2 {
			ox += mx + 3
			y = oy
			mx = 0
		}

		writeAt(ox, y, r.Name, termbox.ColorWhite, bg)
		if len(r.Name) > mx {
			mx = len(r.Name)
		}

		for j, byline := range bylines {
			writeAt(ox, y+j+1, byline, termbox.ColorMagenta, bg)
			if len(byline) > mx {
				mx = len(byline)
			}
		}

		url := r.URL()
		writeAt(ox, y+len(bylines)+1, url, termbox.ColorBlue, bg)
		if len(url) > mx {
			mx = len(url)
		}

		y += 3 + len(bylines)
	}
}

func drawList() {
	for i, item := range list.CurrentPage() {
		fg := termbox.ColorDefault
		bg := termbox.ColorDefault
		if i == list.PagePos {
			fg = termbox.ColorWhite
			bg = termbox.ColorBlue
		}
		if item.Type == ITEM_TUNE {
			tune := hvsc.FilteredTunes[item.TuneIndex]
			if player.CurrentTune != nil && player.CurrentTune.Index == tune.Index {
				fg |= termbox.AttrBold
			}
			writeAt(0, 1+i, fmt.Sprintf(" %-32s %4s", tune.ListName(), tune.Year()), fg, bg)
		} else {
			folder := []rune(item.Name[1:])
			if len(folder) > 40 {
				folder = folder[len(folder)-40 : len(folder)]
				folder[0] = '…'
			}
			writeAt(0, 1+i, string(folder), fg|termbox.AttrBold, bg)
		}
	}
}

func writeAt(x, y int, value string, fg, bg termbox.Attribute) {
	i := 0
	for _, c := range value {
		termbox.SetCell(x+i, y, c, fg, bg)
		i++
	}
}

func lineSplit(s string, w int) []string {
	words := strings.Fields(s)
	lines := make([]string, 0)
	line := bytes.Buffer{}
	for _, word := range words {
		if line.Len() > 0 && line.Len()+len(word) > w {
			lines = append(lines, line.String())
			line = bytes.Buffer{}
		}
		if line.Len() > 0 {
			line.WriteRune(' ')
		}
		line.WriteString(word)
	}
	lines = append(lines, line.String())
	return lines
}
<commit_msg>Scroll pages using mouse wheel.<commit_after>package ui

import (
	"bytes"
	"fmt"
	"log"
	"sort"
	"strings"
	"time"

	"github.com/lhz/sidpicker/csdb"
	"github.com/lhz/sidpicker/hvsc"
	"github.com/lhz/sidpicker/player"
	"github.com/nsf/termbox-go"
)

const (
	MODE_BROWSE = iota
	MODE_SEARCH
)

var w, h int
var list *List
var mode int
var debugInfo string
var searchTerm []rune
var searchCursorPos int
var quit = false

func Setup(initialSearch string) {
	err := termbox.Init()
	if err != nil {
		log.Panicln(err)
	}

	w, h = termbox.Size()

	if len(initialSearch) > 0 {
		searchTerm = []rune(initialSearch)
		hvsc.Filter(string(searchTerm))
	}

	list = NewList(h - 2)

	termbox.SetInputMode(termbox.InputEsc | termbox.InputMouse)
	draw()
}

func Run() {
	defer termbox.Close()

	mode = MODE_BROWSE

	tickChan := time.NewTicker(1 * time.Second).C

	eventChan := make(chan termbox.Event)
	go func() {
		for {
			eventChan <- termbox.PollEvent()
		}
	}()

	for !quit {
		// debugInfo = ""
		select {
		case ev := <-eventChan:
			switch ev.Type {
			case termbox.EventKey:
				keyEvent(ev)
				draw()
			case termbox.EventMouse:
				mouseEvent(ev)
				draw()
			case termbox.EventResize:
				resizeEvent(ev)
				draw()
			case termbox.EventError:
				panic(ev.Err)
			}
		case <-tickChan:
			if player.Playing {
				draw()
			}
		}
	}
}

func resizeEvent(ev termbox.Event) {
	w, h = ev.Width, ev.Height
	draw()
}

func keyEvent(ev termbox.Event) {
	if mode == MODE_SEARCH {
		keyEventSearch(ev)
		return
	}
	switch ev.Key {
	case termbox.KeyCtrlC, termbox.KeyEsc:
		if player.Playing {
			player.Stop()
		} else {
			quit = true
		}
	case termbox.KeyPgup:
		list.PrevPage()
	case termbox.KeyPgdn:
		list.NextPage()
	case termbox.KeyArrowUp:
		list.PrevTune()
	case termbox.KeyArrowDown:
		list.NextTune()
	case termbox.KeyArrowLeft:
		player.PrevSong()
	case termbox.KeyArrowRight:
		player.NextSong()
	case termbox.KeyEnter:
		player.Play(list.CurrentItem().TuneIndex, -1)
		sort.Sort(csdb.ByDate(player.CurrentTune.Releases))
	case termbox.KeySpace:
		list.NextTune()
		player.Play(list.CurrentItem().TuneIndex, -1)
		sort.Sort(csdb.ByDate(player.CurrentTune.Releases))
	case termbox.KeyDelete:
		player.Stop()
	case 0:
		if n := strings.IndexRune("0123456789", ev.Ch); n > 0 {
			if player.Playing && n <= player.CurrentTune.Header.Songs {
				player.PlaySub(n)
			}
			return
		}
		if ev.Ch == '/' {
			mode = MODE_SEARCH
		}
	default:
		debugInfo = string(ev.Key)
	}
}

func keyEventSearch(ev termbox.Event) {
	switch ev.Key {
	case termbox.KeyCtrlC, termbox.KeyEsc:
		mode = MODE_BROWSE
	case termbox.KeyArrowLeft:
		if searchCursorPos > 0 {
			searchCursorPos--
		}
	case termbox.KeyArrowRight:
		if searchCursorPos < len(searchTerm) {
			searchCursorPos++
		}
	case termbox.KeyEnter:
		if hvsc.Filter(string(searchTerm)) {
			list = NewList(h - 2)
			mode = MODE_BROWSE
		}
	case termbox.KeySpace:
		searchInsert(rune(' '))
	case 0:
		searchInsert(ev.Ch)
	case 0x7F:
		if searchCursorPos > 0 {
			searchTerm = append(searchTerm[0:searchCursorPos-1], searchTerm[searchCursorPos:len(searchTerm)]...)
			searchCursorPos--
		}
	default:
		debugInfo = string(ev.Key)
	}
}

func mouseEvent(ev termbox.Event) {
	switch ev.Key {
	case termbox.MouseLeft:
		x := ev.MouseX
		y := ev.MouseY
		if x < 38 && y > 0 && y < h - 1 {
			if list.TuneAtPos(y - 1) {
				player.Play(list.CurrentItem().TuneIndex, -1)
				sort.Sort(csdb.ByDate(player.CurrentTune.Releases))
			}
		}
	case termbox.MouseWheelUp:
		list.PrevPage()
	case termbox.MouseWheelDown:
		list.NextPage()
	}
}

func searchInsert(ch rune) {
	searchTerm = append(searchTerm, rune(' '))
	copy(searchTerm[searchCursorPos+1:], searchTerm[searchCursorPos:])
	searchTerm[searchCursorPos] = ch
	searchCursorPos++
}

func draw() {
	termbox.Clear(termbox.ColorDefault, termbox.ColorDefault)
	drawHeader()
	drawList()
	drawTuneInfo()
	drawReleases()
	drawFooter()
	termbox.Flush()
}

func drawHeader() {
	var header string
	bg := termbox.ColorBlack
	switch mode {
	case MODE_BROWSE:
		header = fmt.Sprintf("Search: %s", string(searchTerm))
		termbox.HideCursor()
	case MODE_SEARCH:
		header = fmt.Sprintf("Search: %s", string(searchTerm))
		bg = termbox.ColorMagenta
		termbox.SetCursor(8+searchCursorPos, 0)
	}
	header = fmt.Sprintf(fmt.Sprintf("%%s%%%ds", w-len([]rune(header))), header, "")
	writeAt(0, 0, header, termbox.ColorWhite|termbox.AttrBold, bg)
}

func drawFooter() {
	footer := fmt.Sprintf("%d/%d  %s", list.CurrentItem().TuneIndex+1, hvsc.NumFilteredTunes, debugInfo)
	footer = fmt.Sprintf(fmt.Sprintf("%%s%%%ds", w-len([]rune(footer))), footer, "")
	writeAt(0, h-1, footer, termbox.ColorWhite, termbox.ColorBlack)
}

func drawTuneInfo() {
	if !player.Playing {
		return
	}
	tune := player.CurrentTune
	ox := 42
	oy := 2
	fg := termbox.ColorDefault
	bg := termbox.ColorDefault

	writeAt(ox, oy+0, fmt.Sprintf("Title:    %s", tune.Title()), fg, bg)
	writeAt(ox, oy+1, fmt.Sprintf("Author:   %s", tune.Header.Author), fg, bg)
	writeAt(ox, oy+2, fmt.Sprintf("Released: %s", tune.Header.Released), fg, bg)

	writeAt(ox, oy+4, fmt.Sprintf("Tune: %d/%d  Length: %s  Time: %s",
		player.CurrentSong, tune.Header.Songs, player.SongLength(), player.Elapsed()), fg, bg)

	if len(tune.Info) == 0 {
		return
	}

	writeAt(ox, oy+6, "STIL Information:", termbox.ColorYellow|termbox.AttrBold, termbox.ColorBlack)

	for i, line := range tune.Info {
		if oy+8+i > h-2 {
			break
		}
		writeAt(ox, oy+8+i, line, fg, bg)
	}
}

func drawReleases() {
	if !player.Playing {
		return
	}
	tune := player.CurrentTune
	if len(tune.Releases) == 0 {
		return
	}

	ox := 42
	oy := 8
	mx := 0
	if len(tune.Info) > 0 {
		oy = oy + 3 + len(tune.Info)
	}

	//fg := termbox.ColorDefault
	bg := termbox.ColorDefault

	line := fmt.Sprintf("Known Releases: %d", len(tune.Releases))
	writeAt(ox, oy, line, termbox.ColorYellow|termbox.AttrBold, termbox.ColorBlack)

	oy += 2
	y := oy

	for _, r := range tune.Releases {

		credits := make([]string, 0)
		if r.Date != "" {
			credits = append(credits, r.Date)
		}
		if len(r.Groups) > 0 {
			credits = append(credits, strings.Join(r.Groups, ", "))
		}

		bylines := lineSplit(strings.Join(credits, " by "), 36)
		if y+len(bylines)+1 > h-2 {
			ox += mx + 3
			y = oy
			mx = 0
		}

		writeAt(ox, y, r.Name, termbox.ColorWhite, bg)
		if len(r.Name) > mx {
			mx = len(r.Name)
		}

		for j, byline := range bylines {
			writeAt(ox, y+j+1, byline, termbox.ColorMagenta, bg)
			if len(byline) > mx {
				mx = len(byline)
			}
		}

		url := r.URL()
		writeAt(ox, y+len(bylines)+1, url, termbox.ColorBlue, bg)
		if len(url) > mx {
			mx = len(url)
		}

		y += 3 + len(bylines)
	}
}

func drawList() {
	for i, item := range list.CurrentPage() {
		fg := termbox.ColorDefault
		bg := termbox.ColorDefault
		if i == list.PagePos {
			fg = termbox.ColorWhite
			bg = termbox.ColorBlue
		}
		if item.Type == ITEM_TUNE {
			tune := hvsc.FilteredTunes[item.TuneIndex]
			if player.CurrentTune != nil && player.CurrentTune.Index == tune.Index {
				fg |= termbox.AttrBold
			}
			writeAt(0, 1+i, fmt.Sprintf(" %-32s %4s", tune.ListName(), tune.Year()), fg, bg)
		} else {
			folder := []rune(item.Name[1:])
			if len(folder) > 40 {
				folder = folder[len(folder)-40 : len(folder)]
				folder[0] = '…'
			}
			writeAt(0, 1+i, string(folder), fg|termbox.AttrBold, bg)
		}
	}
}

func writeAt(x, y int, value string, fg, bg termbox.Attribute) {
	i := 0
	for _, c := range value {
		termbox.SetCell(x+i, y, c, fg, bg)
		i++
	}
}

func lineSplit(s string, w int) []string {
	words := strings.Fields(s)
	lines := make([]string, 0)
	line := bytes.Buffer{}
	for _, word := range words {
		if line.Len() > 0 && line.Len()+len(word) > w {
			lines = append(lines, line.String())
			line = bytes.Buffer{}
		}
		if line.Len() > 0 {
			line.WriteRune(' ')
		}
		line.WriteString(word)
	}
	lines = append(lines, line.String())
	return lines
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/md5"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strconv"
	"text/template"
	"time"
)

const downloadDir1 = "//home//ubuntu//upload//"

// upload logic
func upload1Handler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("upload 1 method:", r.Method)
	if r.Method == "GET" {
		fmt.Println("upload 1 GET:")
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("upload1.html")
		t.Execute(w, token)
	} else {
		log.Printf("Received files upload1")
		r.ParseMultipartForm(32 << 20)
		file, handler, err := r.FormFile("uploadfile")
		if err != nil {
			log.Printf("Error Uploading File")
			fmt.Println(err)
			return
		}
		log.Printf("File : %s", file)
		defer file.Close()
		fmt.Fprintf(w, "%v", handler.Header)
		f, err := os.OpenFile(downloadDir1+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
		if err != nil {
			log.Printf("Error Uploading File")
			fmt.Println(err)
			return
		}
		defer f.Close()
		io.Copy(f, file)
	}
}
<commit_msg>Test multi upload<commit_after>package main

import (
	"crypto/md5"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"text/template"
	"time"
)

const downloadDir1 = "//home//ubuntu//upload//"

const maxMemory = 1 * 1024 * 1024

// upload logic
func upload1Handler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("upload 1 method:", r.Method)
	if r.Method == "GET" {
		fmt.Println("upload 1 GET:")
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("upload1.html")
		t.Execute(w, token)
	} else {
		if err := r.ParseMultipartForm(maxMemory); err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusForbidden)
		}

		for key, value := range r.MultipartForm.Value {
			fmt.Fprintf(w, "%s:%s ", key, value)
			log.Printf("%s:%s", key, value)
		}

		for _, fileHeaders := range r.MultipartForm.File {
			for _, fileHeader := range fileHeaders {
				file, _ := fileHeader.Open()
				path := fmt.Sprintf("%s/%s", downloadDir1, fileHeader.Filename)
				buf, _ := ioutil.ReadAll(file)
				ioutil.WriteFile(path, buf, os.ModePerm)
			}
		}
	}

}
<|endoftext|>


<commit_before>package arn

// Register a list of supported character roles.
func init() {
	DataLists["anime-character-roles"] = []*Option{
		{"main", "Main character"},
		{"supporting", "Supporting character"},
	}
}

// AnimeCharacter ...
type AnimeCharacter struct {
	CharacterID string `json:"characterId" editable:"true"`
	Role        string `json:"role" editable:"true" datalist:"anime-character-roles"`
}

// Character ...
func (char *AnimeCharacter) Character() *Character {
	character, _ := GetCharacter(char.CharacterID)
	return character
}
<commit_msg>Added "Unknown" character role<commit_after>package arn

// Register a list of supported character roles.
func init() {
	DataLists["anime-character-roles"] = []*Option{
		{"", "Unknown"},
		{"main", "Main character"},
		{"supporting", "Supporting character"},
	}
}

// AnimeCharacter ...
type AnimeCharacter struct {
	CharacterID string `json:"characterId" editable:"true"`
	Role        string `json:"role" editable:"true" datalist:"anime-character-roles"`
}

// Character ...
func (char *AnimeCharacter) Character() *Character {
	character, _ := GetCharacter(char.CharacterID)
	return character
}
<|endoftext|>


<commit_before>package vcs

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"text/template"
	"time"

	"github.com/timeglass/glass/_vendor/github.com/hashicorp/errwrap"
)

var TimeSpentNotesRef = "time-spent"

const (
	TOTAL_PREFIX = "total="
)

var PrepCommitTmpl = template.Must(template.New("name").Parse(`#!/bin/sh
# only add time to template and message sources
# @see http://git-scm.com/docs/githooks#_prepare_commit_msg
case "$2" in
message|template)
	printf "$(cat $1)$(glass status)" > "$1" ;;
esac
`))

var PostCommitTmpl = template.Must(template.New("name").Parse(`#!/bin/sh
#persist (punch) to newly created commit and reset the timer
glass status -t "{{.}}" | glass punch
glass reset
`))

var PrePushTmpl = template.Must(template.New("name").Parse(`#!/bin/sh
#push time data
glass push $1 --from-hook
`))

type gitTimeData struct {
	total time.Duration
}

func (g *gitTimeData) Total() time.Duration { return g.total }

type Git struct {
	dir string
}

func NewGit(dir string) *Git {
	return &Git{
		dir: filepath.Join(dir, ".git"),
	}
}

func (g *Git) DefaultRemote() string { return "origin" }
func (g *Git) Name() string          { return "git" }
func (g *Git) IsAvailable() bool {
	fi, err := os.Stat(g.dir)
	if err != nil || !fi.IsDir() {
		return false
	}

	return true
}

func (g *Git) Show(commit string) (TimeData, error) {
	data := &gitTimeData{}
	args := []string{"notes", "--ref=" + TimeSpentNotesRef, "show", commit}
	outbuff := bytes.NewBuffer(nil)
	errbuff := bytes.NewBuffer(nil)
	cmd := exec.Command("git", args...)
	cmd.Stdout = outbuff
	cmd.Stderr = errbuff

	err := cmd.Run()
	if err != nil && strings.Contains(errbuff.String(), "No note found for object") {
		return data, ErrNoCommitTimeData
	}

	//in other cases present user with git output
	_, err2 := io.Copy(os.Stderr, errbuff)
	if err2 != nil {
		return data, err
	}

	if err != nil {
		return data, errwrap.Wrapf(fmt.Sprintf("Failed to show time for commit '%s' using git args %s: {{err}}", commit, args), err)
	}

	//scan lines in note
	scanner := bufio.NewScanner(outbuff)
	for scanner.Scan() {
		line := scanner.Text()

		//@todo for now only read total line
		if strings.HasPrefix(line, TOTAL_PREFIX) {
			t, err := time.ParseDuration(line[len(TOTAL_PREFIX):])
			if err != nil {
				return data, errwrap.Wrapf(fmt.Sprintf("Failed to parse time from line '%s': {{err}}"), err)
			}

			data.total = t
		}
	}
	if err := scanner.Err(); err != nil {
		return data, errwrap.Wrapf(fmt.Sprintf("Failed to scan note for commit '%s': {{err}}"), err)
	}

	return data, nil
}

func (g *Git) Persist(t time.Duration) error {
	args := []string{"notes", "--ref=" + TimeSpentNotesRef, "add", "-f", "-m", fmt.Sprintf("%s%s", TOTAL_PREFIX, t)}
	cmd := exec.Command("git", args...)
	err := cmd.Run()
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to persist time '%s' using git command %s: {{err}}", t, args), err)
	}

	return nil
}

func (g *Git) Pull(remote string) error {
	args := []string{"fetch", remote, fmt.Sprintf("refs/notes/%s:refs/notes/%s", TimeSpentNotesRef, TimeSpentNotesRef)}
	cmd := exec.Command("git", args...)
	buff := bytes.NewBuffer(nil)

	cmd.Stdout = os.Stdout
	cmd.Stderr = buff

	err := cmd.Run()
	if err != nil && strings.Contains(buff.String(), "Couldn't find remote ref") {
		return ErrNoRemoteTimeData
	}

	//in other cases present user with git output
	_, err2 := io.Copy(os.Stderr, buff)
	if err2 != nil {
		return err
	}

	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to fetch from remote '%s' using git command %s: {{err}}", remote, args), err)
	}

	return nil
}

func (g *Git) Push(remote string, refs string) error {

	//if time ref is already pushed, dont do it again
	if strings.Contains(refs, TimeSpentNotesRef) {
		return nil
	}

	args := []string{"push", remote, fmt.Sprintf("refs/notes/%s", TimeSpentNotesRef)}
	cmd := exec.Command("git", args...)
	buff := bytes.NewBuffer(nil)

	cmd.Stdout = os.Stdout
	cmd.Stderr = buff

	err := cmd.Run()
	if err != nil && strings.Contains(buff.String(), "src refspec refs/notes/"+TimeSpentNotesRef+" does not match any") {
		return ErrNoLocalTimeData
	}

	//in other cases present user with git output
	_, err2 := io.Copy(os.Stderr, buff)
	if err2 != nil {
		return err
	}

	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to push to remote '%s' using git command %s: {{err}}", remote, args), err)
	}

	return nil
}

func (g *Git) Hook() error {
	hpath := filepath.Join(g.dir, "hooks")

	//prepare commit msg: status()
	prepcopath := filepath.Join(hpath, "prepare-commit-msg")
	prepcof, err := os.Create(prepcopath)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to create prepare-commit-msg  '%s': {{err}}", prepcof.Name()), err)
	}

	err = os.Chmod(prepcopath, 0766)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to make prepare-commit-msg file '%s' executable: {{err}}", hpath), err)
	}

	err = PrepCommitTmpl.Execute(prepcof, struct{}{})
	if err != nil {
		return errwrap.Wrapf("Failed to run post-commit template: {{err}}", err)
	}

	//post commit: lap()
	postcopath := filepath.Join(hpath, "post-commit")
	postcof, err := os.Create(postcopath)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to create post-commit '%s': {{err}}", postcof.Name()), err)
	}

	err = os.Chmod(postcopath, 0766)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to make post-commit file '%s' executable: {{err}}", hpath), err)
	}

	err = PostCommitTmpl.Execute(postcof, struct{}{})
	if err != nil {
		return errwrap.Wrapf("Failed to run post-commit template: {{err}}", err)
	}

	//post receive: push()
	prepushpath := filepath.Join(hpath, "pre-push")
	prepushf, err := os.Create(prepushpath)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to create pre-push  '%s': {{err}}", prepushf.Name()), err)
	}

	err = os.Chmod(prepushpath, 0766)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to make pre-push file '%s' executable: {{err}}", hpath), err)
	}

	err = PrePushTmpl.Execute(prepushf, struct{}{})
	if err != nil {
		return errwrap.Wrapf("Failed to run pre-push template: {{err}}", err)
	}

	return nil
}
<commit_msg>fixed post commit hook [spent 6m0s]<commit_after>package vcs

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"text/template"
	"time"

	"github.com/timeglass/glass/_vendor/github.com/hashicorp/errwrap"
)

var TimeSpentNotesRef = "time-spent"

const (
	TOTAL_PREFIX = "total="
)

var PrepCommitTmpl = template.Must(template.New("name").Parse(`#!/bin/sh
# only add time to template and message sources
# @see http://git-scm.com/docs/githooks#_prepare_commit_msg
case "$2" in
message|template)
	printf "$(cat $1)$(glass status)" > "$1" ;;
esac
`))

var PostCommitTmpl = template.Must(template.New("name").Parse(`#!/bin/sh
#persist (punch) to newly created commit and reset the timer
glass status -t "{{"{{"}}.{{"}}"}}" | glass punch
glass reset
`))

var PrePushTmpl = template.Must(template.New("name").Parse(`#!/bin/sh
#push time data
glass push $1 --from-hook
`))

type gitTimeData struct {
	total time.Duration
}

func (g *gitTimeData) Total() time.Duration { return g.total }

type Git struct {
	dir string
}

func NewGit(dir string) *Git {
	return &Git{
		dir: filepath.Join(dir, ".git"),
	}
}

func (g *Git) DefaultRemote() string { return "origin" }
func (g *Git) Name() string          { return "git" }
func (g *Git) IsAvailable() bool {
	fi, err := os.Stat(g.dir)
	if err != nil || !fi.IsDir() {
		return false
	}

	return true
}

func (g *Git) Show(commit string) (TimeData, error) {
	data := &gitTimeData{}
	args := []string{"notes", "--ref=" + TimeSpentNotesRef, "show", commit}
	outbuff := bytes.NewBuffer(nil)
	errbuff := bytes.NewBuffer(nil)
	cmd := exec.Command("git", args...)
	cmd.Stdout = outbuff
	cmd.Stderr = errbuff

	err := cmd.Run()
	if err != nil && strings.Contains(errbuff.String(), "No note found for object") {
		return data, ErrNoCommitTimeData
	}

	//in other cases present user with git output
	_, err2 := io.Copy(os.Stderr, errbuff)
	if err2 != nil {
		return data, err
	}

	if err != nil {
		return data, errwrap.Wrapf(fmt.Sprintf("Failed to show time for commit '%s' using git args %s: {{err}}", commit, args), err)
	}

	//scan lines in note
	scanner := bufio.NewScanner(outbuff)
	for scanner.Scan() {
		line := scanner.Text()

		//@todo for now only read total line
		if strings.HasPrefix(line, TOTAL_PREFIX) {
			t, err := time.ParseDuration(line[len(TOTAL_PREFIX):])
			if err != nil {
				return data, errwrap.Wrapf(fmt.Sprintf("Failed to parse time from line '%s': {{err}}"), err)
			}

			data.total = t
		}
	}
	if err := scanner.Err(); err != nil {
		return data, errwrap.Wrapf(fmt.Sprintf("Failed to scan note for commit '%s': {{err}}"), err)
	}

	return data, nil
}

func (g *Git) Persist(t time.Duration) error {
	args := []string{"notes", "--ref=" + TimeSpentNotesRef, "add", "-f", "-m", fmt.Sprintf("%s%s", TOTAL_PREFIX, t)}
	cmd := exec.Command("git", args...)
	err := cmd.Run()
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to persist time '%s' using git command %s: {{err}}", t, args), err)
	}

	return nil
}

func (g *Git) Pull(remote string) error {
	args := []string{"fetch", remote, fmt.Sprintf("refs/notes/%s:refs/notes/%s", TimeSpentNotesRef, TimeSpentNotesRef)}
	cmd := exec.Command("git", args...)
	buff := bytes.NewBuffer(nil)

	cmd.Stdout = os.Stdout
	cmd.Stderr = buff

	err := cmd.Run()
	if err != nil && strings.Contains(buff.String(), "Couldn't find remote ref") {
		return ErrNoRemoteTimeData
	}

	//in other cases present user with git output
	_, err2 := io.Copy(os.Stderr, buff)
	if err2 != nil {
		return err
	}

	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to fetch from remote '%s' using git command %s: {{err}}", remote, args), err)
	}

	return nil
}

func (g *Git) Push(remote string, refs string) error {

	//if time ref is already pushed, dont do it again
	if strings.Contains(refs, TimeSpentNotesRef) {
		return nil
	}

	args := []string{"push", remote, fmt.Sprintf("refs/notes/%s", TimeSpentNotesRef)}
	cmd := exec.Command("git", args...)
	buff := bytes.NewBuffer(nil)

	cmd.Stdout = os.Stdout
	cmd.Stderr = buff

	err := cmd.Run()
	if err != nil && strings.Contains(buff.String(), "src refspec refs/notes/"+TimeSpentNotesRef+" does not match any") {
		return ErrNoLocalTimeData
	}

	//in other cases present user with git output
	_, err2 := io.Copy(os.Stderr, buff)
	if err2 != nil {
		return err
	}

	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to push to remote '%s' using git command %s: {{err}}", remote, args), err)
	}

	return nil
}

func (g *Git) Hook() error {
	hpath := filepath.Join(g.dir, "hooks")

	//prepare commit msg: status()
	prepcopath := filepath.Join(hpath, "prepare-commit-msg")
	prepcof, err := os.Create(prepcopath)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to create prepare-commit-msg  '%s': {{err}}", prepcof.Name()), err)
	}

	err = os.Chmod(prepcopath, 0766)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to make prepare-commit-msg file '%s' executable: {{err}}", hpath), err)
	}

	err = PrepCommitTmpl.Execute(prepcof, struct{}{})
	if err != nil {
		return errwrap.Wrapf("Failed to run post-commit template: {{err}}", err)
	}

	//post commit: lap()
	postcopath := filepath.Join(hpath, "post-commit")
	postcof, err := os.Create(postcopath)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to create post-commit '%s': {{err}}", postcof.Name()), err)
	}

	err = os.Chmod(postcopath, 0766)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to make post-commit file '%s' executable: {{err}}", hpath), err)
	}

	err = PostCommitTmpl.Execute(postcof, struct{}{})
	if err != nil {
		return errwrap.Wrapf("Failed to run post-commit template: {{err}}", err)
	}

	//post receive: push()
	prepushpath := filepath.Join(hpath, "pre-push")
	prepushf, err := os.Create(prepushpath)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to create pre-push  '%s': {{err}}", prepushf.Name()), err)
	}

	err = os.Chmod(prepushpath, 0766)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("Failed to make pre-push file '%s' executable: {{err}}", hpath), err)
	}

	err = PrePushTmpl.Execute(prepushf, struct{}{})
	if err != nil {
		return errwrap.Wrapf("Failed to run pre-push template: {{err}}", err)
	}

	return nil
}
<|endoftext|>


<commit_before>package egoscale

// Version of the library
const Version = "0.14.1"
<commit_msg>prepare release<commit_after>package egoscale

// Version of the library
const Version = "0.14.2"
<|endoftext|>


<commit_before>// AUTOGENERATED: DO NOT EDIT

package kayvee

// Version is a string containing the version of this library.
var Version = "6.2.0"
<commit_msg>Bump to v6.3.0<commit_after>// AUTOGENERATED: DO NOT EDIT

package kayvee

// Version is a string containing the version of this library.
var Version = "6.3.0"
<|endoftext|>


<commit_before>package main

const (
	version = "0.1.0"
)
<commit_msg>bump version to 0.1.1<commit_after>package main

const (
	version = "0.1.1"
)
<|endoftext|>


<commit_before>package gf

const VERSION  = "v1.5.10"
const AUTHORS  = "john<john@goframe.org>"

<commit_msg>VERSION updates<commit_after>package gf

const VERSION  = "v1.5.12"
const AUTHORS  = "john<john@goframe.org>"

<|endoftext|>


<commit_before>package soko

const Version = "0.1.0.rc2"
<commit_msg>First release of soko 0.1.0<commit_after>package soko

const Version = "0.1.0"
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"log"

	"github.com/cubicdaiya/nginx-build/builder"
)

func versionsSubmajorGen(major, submajor, minor int) []string {
	var versions []string

	for i := 0; i <= minor; i++ {
		v := fmt.Sprintf("%d.%d.%d", major, submajor, i)
		versions = append(versions, v)
	}
	return versions
}

func versionsGen() []string {
	var versions []string
	// 0.x.x
	versionsMinor0 := []int{45, 6, 61, 14, 38, 39, 69, 55, 7}
	// 1.x.x
	versionsMinor1 := []int{15, 19, 9, 16, 7, 13, 3, 12, 1, 15, 2, 7}

	// 0.1.0 ~ 0.9.7
	for i := 0; i < len(versionsMinor0); i++ {
		versions = append(versions, versionsSubmajorGen(0, i+1, versionsMinor0[i])...)
	}

	// 1.0.0 ~
	for i := 0; i < len(versionsMinor1); i++ {
		versions = append(versions, versionsSubmajorGen(1, i, versionsMinor1[i])...)
	}

	return versions
}

func versionsGenOpenResty() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("openresty-%s", builder.OpenRestyVersion))

	return versions
}

func versionsGenTengine() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("tengine-%s", builder.TengineVersion))

	return versions
}

func printNginxVersions() {
	versions := versionsGen()
	versions = append(versions, versionsGenOpenResty()...)
	versions = append(versions, versionsGenTengine()...)
	for _, v := range versions {
		fmt.Println(v)
	}
}

func versionCheck(version string) {
	if len(version) == 0 {
		log.Println("[warn]nginx version is not set.")
		log.Printf("[warn]nginx-build use %s.\n", builder.NginxVersion)
	}
}
<commit_msg>style: newlined versions.<commit_after>package main

import (
	"fmt"
	"log"

	"github.com/cubicdaiya/nginx-build/builder"
)

func versionsSubmajorGen(major, submajor, minor int) []string {
	var versions []string

	for i := 0; i <= minor; i++ {
		v := fmt.Sprintf("%d.%d.%d", major, submajor, i)
		versions = append(versions, v)
	}
	return versions
}

func versionsGen() []string {
	var versions []string
	// 0.x.x
	versionsMinor0 := []int{
		45, // 0.1.x
		6,  // 0.2.x
		61, // 0.3.x
		14, // 0.4.x
		38, // 0.5.x
		39, // 0.6.x
		69, // 0.7.x
		55, // 0.8.x
		7,  // 0.9.x
	}
	// 1.x.x
	versionsMinor1 := []int{
		15, // 1.0.x
		19, // 1.1.x
		9,  // 1.2.x
		16, // 1.3.x
		7,  // 1.4.x
		13, // 1.5.x
		3,  // 1.6.x
		12, // 1.7.x
		1,  // 1.8.x
		15, // 1.9.x
		2,  // 1.10.x
		7,  // 1.11.x
	}

	// 0.1.0 ~ 0.9.7
	for i := 0; i < len(versionsMinor0); i++ {
		versions = append(versions, versionsSubmajorGen(0, i+1, versionsMinor0[i])...)
	}

	// 1.0.0 ~
	for i := 0; i < len(versionsMinor1); i++ {
		versions = append(versions, versionsSubmajorGen(1, i, versionsMinor1[i])...)
	}

	return versions
}

func versionsGenOpenResty() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("openresty-%s", builder.OpenRestyVersion))

	return versions
}

func versionsGenTengine() []string {
	var versions []string

	versions = append(versions, fmt.Sprintf("tengine-%s", builder.TengineVersion))

	return versions
}

func printNginxVersions() {
	versions := versionsGen()
	versions = append(versions, versionsGenOpenResty()...)
	versions = append(versions, versionsGenTengine()...)
	for _, v := range versions {
		fmt.Println(v)
	}
}

func versionCheck(version string) {
	if len(version) == 0 {
		log.Println("[warn]nginx version is not set.")
		log.Printf("[warn]nginx-build use %s.\n", builder.NginxVersion)
	}
}
<|endoftext|>


<commit_before>package main

const Version = "0.1.3"
<commit_msg>feat(version): bump<commit_after>package main

const Version = "0.1.4"
<|endoftext|>


<commit_before>package main

const VERSION = "0.3.1"
<commit_msg>bump version to v0.3.2<commit_after>package main

const VERSION = "0.3.2"
<|endoftext|>


<commit_before>package main

const VERSION = "0.9.1"
<commit_msg>:+1: Bump up the version 0.9.2-alpha1<commit_after>package main

const VERSION = "0.9.2-alpha1"
<|endoftext|>