// refreshWallets scans the USB devices attached to the machine and updates the
// list of wallets based on the found devices.
772363
func (hub *Hub) refreshWallets() {
	// Don't scan the USB like crazy it the user fetches wallets in a loop
	hub.stateLock.RLock()
	elapsed := time.Since(hub.refreshed)
	hub.stateLock.RUnlock()

	if elapsed < refreshThrottling {
		return
	}
	// Retrieve the current list of USB wallet devices
	var devices []hid.DeviceInfo

	if runtime.GOOS == "linux" {
		// hidapi on Linux opens the device during enumeration to retrieve some infos,
		// breaking the Ledger protocol if that is waiting for user confirmation. This
		// is a bug acknowledged at Ledger, but it won't be fixed on old devices so we
		// need to prevent concurrent comms ourselves. The more elegant solution would
		// be to ditch enumeration in favor of hotplug events, but that don't work yet
		// on Windows so if we need to hack it anyway, this is more elegant for now.
		hub.commsLock.Lock()
		if hub.commsPend > 0 { // A confirmation is pending, don't refresh
			hub.commsLock.Unlock()
			return
		}
	}
	for _, info := range hid.Enumerate(hub.vendorID, 0) {
		for _, id := range hub.productIDs {
			if info.ProductID == id && (info.UsagePage == hub.usageID || info.Interface == hub.endpointID) {
				devices = append(devices, info)
				break
			}
		}
	}
	if runtime.GOOS == "linux" {
		// See rationale before the enumeration why this is needed and only on Linux.
		hub.commsLock.Unlock()
	}
	// Transform the current list of wallets into the new one
	hub.stateLock.Lock()

	var (
		wallets = make([]accounts.Wallet, 0, len(devices))
		events  []accounts.WalletEvent
	)

	for _, device := range devices {
		url := accounts.URL{Scheme: hub.scheme, Path: device.Path}

		// Drop wallets in front of the next device or those that failed for some reason
		for len(hub.wallets) > 0 {
			// Abort if we're past the current device and found an operational one
			_, failure := hub.wallets[0].Status()
			if hub.wallets[0].URL().Cmp(url) >= 0 || failure == nil {
				break
			}
			// Drop the stale and failed devices
			events = append(events, accounts.WalletEvent{Wallet: hub.wallets[0], Kind: accounts.WalletDropped})
			hub.wallets = hub.wallets[1:]
		}
		// If there are no more wallets or the device is before the next, wrap new wallet
		if len(hub.wallets) == 0 || hub.wallets[0].URL().Cmp(url) > 0 {
			logger := log.New("url", url)
			wallet := &wallet{hub: hub, driver: hub.makeDriver(logger), url: &url, info: device, log: logger}

			events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletArrived})
			wallets = append(wallets, wallet)
			continue
		}
		// If the device is the same as the first wallet, keep it
		if hub.wallets[0].URL().Cmp(url) == 0 {
			wallets = append(wallets, hub.wallets[0])
			hub.wallets = hub.wallets[1:]
			continue
		}
	}
	// Drop any leftover wallets and set the new batch
	for _, wallet := range hub.wallets {
		events = append(events, accounts.WalletEvent{Wallet: wallet, Kind: accounts.WalletDropped})
	}
	hub.refreshed = time.Now()
	hub.wallets = wallets
	hub.stateLock.Unlock()

	// Fire all wallet events and return
	for _, event := range events {
		hub.updateFeed.Send(event)
	}
}
358137
func (oauth *Oauth) RefreshAccessToken(refreshToken string) (result ResAccessToken, err error) {
	urlStr := fmt.Sprintf(refreshAccessTokenURL, oauth.AppID, refreshToken)
	var response []byte
	response, err = util.HTTPGet(urlStr)
	if err != nil {
		return
	}
	err = json.Unmarshal(response, &result)
	if err != nil {
		return
	}
	if result.ErrCode != 0 {
		err = fmt.Errorf("GetUserAccessToken error : errcode=%v , errmsg=%v", result.ErrCode, result.ErrMsg)
		return
	}
	return
}
691656
func (conn *Connection) Refresh() (err error) {
	urlValues := url.Values{}

	urlValues.Set("grant_type", "password")
	urlValues.Set("client_id", conn.ConsumerKey)
	urlValues.Set("client_secret", conn.ConsumerSecret)
	urlValues.Set("username", conn.Username)
	urlValues.Set("password", conn.Password)

	resp, err := http.PostForm(conn.InstanceUrl+"/services/oauth2/token", urlValues)

	if err != nil {
		return err
	}

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

	if err != nil {
		return err
	}

	result := OAuthResponse{}

	err = json.Unmarshal(body, &result)

	if err != nil {
		return err
	}

	conn.AccessToken = result.AccessToken
	conn.InstanceUrl = result.InstanceUrl

	return nil
}
446453
func (c *Client) RefreshToken(refreshToken string) (*Token, error) {
	params := make(url.Values)
	params.Set("grant_type", GrantTypeRefreshToken)
	params.Set("refresh_token", refreshToken)
	params.Set("scope", "")
	return c.grantToken(params)
}
250536
func (t *tokenWithProvider) refreshTokenWithRetries(ctx context.Context, prev, base *internal.Token) (tok *internal.Token, err error) {
	err = retry.Retry(ctx, transient.Only(retryParams), func() error {
		tok, err = t.provider.RefreshToken(ctx, prev, base)
		return err
	}, nil)
	return
}
613345
func (api *AuthAPI) GetTokensByRefreshToken(refreshtoken string) (tokenOptions *TokenOptions, err error) {
	oidcClient, err := api.buildOIDCClient()
	if err != nil {
		return
	}

	tokenResponse, err := oidcClient.GetTokenByRefreshTokenGrant(refreshtoken)
	if err != nil {
		return
	}

	return api.toTokenOptions(tokenResponse), nil
}
1022233
func (c *client) refreshAuthToken(localCfg *localconfig.LocalConfig, ctxName, configPath string) error {
	if c.RefreshToken == "" {
		// If we have no refresh token, there's no point in doing anything
		return nil
	}
	configCtx, err := localCfg.ResolveContext(ctxName)
	if err != nil {
		return err
	}
	parser := &jwt.Parser{
		SkipClaimsValidation: true,
	}
	var claims jwt.StandardClaims
	_, _, err = parser.ParseUnverified(configCtx.User.AuthToken, &claims)
	if err != nil {
		return err
	}
	if claims.Valid() == nil {
		// token is still valid
		return nil
	}

	log.Debug("Auth token no longer valid. Refreshing")
	rawIDToken, refreshToken, err := c.redeemRefreshToken()
	if err != nil {
		return err
	}
	c.AuthToken = rawIDToken
	c.RefreshToken = refreshToken
	localCfg.UpsertUser(localconfig.User{
		Name:         ctxName,
		AuthToken:    c.AuthToken,
		RefreshToken: c.RefreshToken,
	})
	err = localconfig.WriteLocalConfig(*localCfg, configPath)
	if err != nil {
		return err
	}
	return nil
}
294755
func (s *UIServerAPI) ListWallets() []rawWallet {
	wallets := make([]rawWallet, 0) // return [] instead of nil if empty
	for _, wallet := range s.am.Wallets() {
		status, failure := wallet.Status()

		raw := rawWallet{
			URL:      wallet.URL().String(),
			Status:   status,
			Accounts: wallet.Accounts(),
		}
		if failure != nil {
			raw.Failure = failure.Error()
		}
		wallets = append(wallets, raw)
	}
	return wallets
}
275785
func (f *FirewallsContainer) Refresh(ctx context.Context) {
	reload := false

	f.ids.PfconfigNS = "config::Firewall_SSO"

	// If ids changed, we want to reload
	if !pfconfigdriver.IsValid(ctx, &f.ids) {
		reload = true
	}

	pfconfigdriver.FetchDecodeSocketCache(ctx, &f.ids)

	fssoFactory := NewFactory(ctx)

	if f.Structs != nil {
		for _, firewallId := range f.ids.Keys {
			firewall, ok := f.Structs[firewallId]

			if !ok {
				log.LoggerWContext(ctx).Info("A firewall was added. Will read the firewalls again.")
				reload = true
				break
			}

			if !pfconfigdriver.IsValid(ctx, firewall) {
				log.LoggerWContext(ctx).Info(fmt.Sprintf("Firewall %s has been detected as expired in pfconfig. Reloading.", firewallId))
				reload = true
			}
		}
	} else {
		reload = true
	}

	if reload {
		newFirewalls := make(map[string]FirewallSSOInt)

		for _, firewallId := range f.ids.Keys {
			log.LoggerWContext(ctx).Info(fmt.Sprintf("Adding firewall %s", firewallId))

			firewall, err := fssoFactory.Instantiate(ctx, firewallId)
			if err != nil {
				log.LoggerWContext(ctx).Error(fmt.Sprintf("Cannot instantiate firewall %s because of an error (%s). Ignoring it.", firewallId, err))
			} else {
				newFirewalls[firewall.GetFirewallSSO(ctx).PfconfigHashNS] = firewall
			}
		}
		f.Structs = newFirewalls
	}
}
771987
func (c *Charm) Refresh() error {
	ch, err := c.st.Charm(c.doc.URL)
	if err != nil {
		return errors.Trace(err)
	}
	c.doc = ch.doc
	return nil
}
1194639
func (b BlockServerMeasured) RefreshAuthToken(ctx context.Context) {
	b.delegate.RefreshAuthToken(ctx)
}
908337
func (md *MDServerRemote) RefreshAuthToken(ctx context.Context) {
	md.log.CDebugf(ctx, "MDServerRemote: Refreshing auth token...")

	if v := ctx.Value(ctxMDServerResetKey); v != nil {
		md.log.CDebugf(ctx, "Avoiding resetAuth recursion")
		return
	}

	_, err := md.resetAuth(ctx, md.getClient())
	switch err.(type) {
	case nil:
		md.log.CInfof(ctx, "MDServerRemote: auth token refreshed")
	case idutil.NoCurrentSessionError:
		md.log.CInfof(ctx,
			"MDServerRemote: no session available, connection remains anonymous")
	default:
		md.log.CInfof(ctx,
			"MDServerRemote: error refreshing auth token: %v", err)
		err = md.reconnect()
		if err != nil {
			md.log.CWarningf(ctx,
				"MDServerRemote: error calling md.reconnect(): %v", err)
		}
	}
}
1323039
func (mw *GinJWTMiddleware) RefreshToken(c *gin.Context) (string, time.Time, error) {
	claims, err := mw.CheckIfTokenExpire(c)
	if err != nil {
		return "", time.Now(), err
	}

	// Create the token
	newToken := jwt.New(jwt.GetSigningMethod(mw.SigningAlgorithm))
	newClaims := newToken.Claims.(jwt.MapClaims)

	for key := range claims {
		newClaims[key] = claims[key]
	}

	expire := mw.TimeFunc().Add(mw.Timeout)
	newClaims["exp"] = expire.Unix()
	newClaims["orig_iat"] = mw.TimeFunc().Unix()
	tokenString, err := mw.signedString(newToken)

	if err != nil {
		return "", time.Now(), err
	}

	// set cookie
	if mw.SendCookie {
		maxage := int(expire.Unix() - time.Now().Unix())
		c.SetCookie(
			mw.CookieName,
			tokenString,
			maxage,
			"/",
			mw.CookieDomain,
			mw.SecureCookie,
			mw.CookieHTTPOnly,
		)
	}

	return tokenString, expire, nil
}
198193
func (w *WalletState) Refresh(mctx libkb.MetaContext, accountID stellar1.AccountID, reason string) error {
	a, ok := w.accountState(accountID)
	if !ok {
		return ErrAccountNotFound
	}
	return a.Refresh(mctx, w.G().NotifyRouter, reason)
}
919123
func (fic *fileItemContainer) refreshLocation() {
	if fic.current == nil {
		return
	}
	if fic.isTopNode {
		return
	}
	hash := fic.current.pn.DigestPrefix(10)
	js.Global.Get("history").Call("pushState", hash, "", fic.basePath+"/h"+hash)
}
1129224
func (m *Machine) Refresh() error {
	life, err := common.OneLife(m.facade, m.tag)
	if err != nil {
		return errors.Trace(err)
	}
	m.life = life
	return nil
}
555550
func (poloniex *PoloniexExchange) Refresh() {
	poloniex.LogRequest()

	var response map[string]*PoloniexPair
	err := poloniex.fetch(poloniex.requests.price, &response)
	if err != nil {
		poloniex.fail("Fetch", err)
		return
	}
	market, ok := response[poloniex.CurrencyPair]
	if !ok {
		poloniex.fail("Market not in response", fmt.Errorf("Response did not have expected CurrencyPair %s", poloniex.CurrencyPair))
		return
	}
	price, err := strconv.ParseFloat(market.Last, 64)
	if err != nil {
		poloniex.fail(fmt.Sprintf("Failed to parse float from Last=%s", market.Last), err)
		return
	}
	baseVolume, err := strconv.ParseFloat(market.BaseVolume, 64)
	if err != nil {
		poloniex.fail(fmt.Sprintf("Failed to parse float from BaseVolume=%s", market.BaseVolume), err)
		return
	}
	volume, err := strconv.ParseFloat(market.QuoteVolume, 64)
	if err != nil {
		poloniex.fail(fmt.Sprintf("Failed to parse float from QuoteVolume=%s", market.QuoteVolume), err)
		return
	}
	percentChange, err := strconv.ParseFloat(market.PercentChange, 64)
	if err != nil {
		poloniex.fail(fmt.Sprintf("Failed to parse float from PercentChange=%s", market.PercentChange), err)
		return
	}
	oldPrice := price / (1 + percentChange)

	// Depth chart
	// Check to see if the websocket has been initialized
	var skipHttp, skipBotUpdate bool
	var depth *DepthData
	if !poloniex.wsListening() {
		if poloniex.wsFailed() {
			errCount := poloniex.wsErrorCount()
			if errCount < poloniexMaxErrors {
				// Try to connect, but don't wait for the response. Grab the order
				// book over HTTP anyway.
				poloniex.connectWs()
			} else if errCount == poloniexMaxErrors {
				log.Errorf("Poloniex websocket being disabled. Too many errors")
			}
		} else {
			// Connection has not been initialized. Trigger a silent update, since an
			// update will be triggered on initial websocket message, which contains
			// the full orderbook.
			skipHttp = true
			skipBotUpdate = true
			log.Tracef("Initializing websocket connection for poloniex")
		}
	} else { // Websocket is listening
		depth = poloniex.wsDepths()
		skipHttp = true
	}

	// If not expecting depth data from the websocket, grab it from HTTP
	if !skipHttp {
		depthResponse := new(PoloniexDepthResponse)
		err = poloniex.fetch(poloniex.requests.depth, depthResponse)
		if err != nil {
			log.Errorf("Poloniex depth chart fetch error: %v", err)
		}
		depth = depthResponse.translate()
	}

	// Candlesticks
	state := poloniex.state()

	candlesticks := map[candlestickKey]Candlesticks{}
	for bin, req := range poloniex.requests.candlesticks {
		oldSticks, found := state.Candlesticks[bin]
		if !found || oldSticks.needsUpdate(bin) {
			log.Tracef("Signalling candlestick update for %s, bin size %s", poloniex.token, bin)
			response := new(PoloniexCandlestickResponse)
			err := poloniex.fetch(req, response)
			if err != nil {
				log.Errorf("Error retrieving candlestick data from poloniex for bin size %s: %v", string(bin), err)
				continue
			}

			sticks := response.translate()
			if !found || sticks.time().After(oldSticks.time()) {
				candlesticks[bin] = sticks
			}
		}
	}

	update := &ExchangeState{
		Price:        price,
		BaseVolume:   baseVolume,
		Volume:       volume,
		Change:       price - oldPrice,
		Depth:        depth,
		Candlesticks: candlesticks,
	}
	if skipBotUpdate {
		poloniex.SilentUpdate(update)
		poloniex.connectWs()
	} else {
		poloniex.Update(update)
	}

}