Skip to content

Commit

Permalink
Make changes to support panic session.
Browse files Browse the repository at this point in the history
  • Loading branch information
jigar-f committed Sep 19, 2023
1 parent f32610d commit ff593d0
Show file tree
Hide file tree
Showing 7 changed files with 154 additions and 56 deletions.
66 changes: 49 additions & 17 deletions internalsdk/session_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import (
"encoding/json"
"fmt"
"net/http"
"path/filepath"
"strconv"

"github.com/getlantern/flashlight/v7/common"
"github.com/getlantern/flashlight/v7/logging"
"github.com/getlantern/pathdb"
"github.com/getlantern/pathdb/minisql"
)
Expand Down Expand Up @@ -68,7 +71,7 @@ func NewSessionModel(schema string, mdb minisql.DB) (*SessionModel, error) {
}

// TO check if session model implemnets all method or not
// var s Session = &SessionModel{}
var s Session = &SessionModel{}

func (s *SessionModel) InvokeMethod(method string, arguments minisql.Values) (*minisql.Value, error) {
switch method {
Expand Down Expand Up @@ -212,6 +215,21 @@ func (s *SessionModel) InvokeMethod(method string, arguments minisql.Values) (*m
}
}

// Internal functions that manage method
func (s *SessionModel) StartService(configDir string,
locale string,
settings Settings) {

logging.EnableFileLogging(common.DefaultAppName, filepath.Join(configDir, "logs"))

//Setup login
session := &panickingSessionImpl{s}
startOnce.Do(func() {
go run(configDir, locale, settings, session)
})

}

// InvokeMethod handles method invocations on the SessionModel.
func initSessionModel(m *baseModel, jsonString string) error {
// Init few path for startup
Expand All @@ -232,36 +250,42 @@ func setDeviceId(m *baseModel, deviceID string) error {
}

func (s *SessionModel) GetDeviceID() (string, error) {

byte, err := s.baseModel.db.Get(DEVICE_ID)
panicIfNecessary(err)
//Todo Find better way to deserialize the values
// Also fine generic way
return string(byte), nil
}

// Todo There is some issue with user id changeing it value
// When Coverting from bytes to Float
func (s *SessionModel) GetUserID() (int64, error) {
paymentTestMode, err := s.baseModel.db.Get(PAYMENT_TEST_MODE)
panicIfNecessary(err)
if err != nil {
return 0, err
}
//Todo find way to deserialize the values
paymentTestModeStr := string(paymentTestMode)
if paymentTestModeStr == "true" {
if paymentTestModeStr == "true" && paymentTestModeStr != "" {
// When we're testing payments, use a specific test user ID. This is a user in our
// production environment but that gets special treatment from the proserver to hit
// payment providers' test endpoints.

i64, err := strconv.ParseInt("9007199254740992L", 10, 64)
if err != nil {
return 0, err
}
return i64, nil
} else {
userId, err := s.baseModel.db.Get(USER_ID)
panicIfNecessary(err)
i64, err := strconv.ParseInt(string(userId), 10, 64)
if err != nil {
return 0, err
}
userId = userId[1:]
newUserId, err := BytesToFloat64LittleEndian(userId)
if err != nil {
return 0, err
}
i64 := int64(newUserId)
return i64, nil
}
}
Expand Down Expand Up @@ -295,13 +319,15 @@ func (s *SessionModel) UpdateAdSettings(adsetting AdSettings) error {
return nil
}

func (s *SessionModel) UpdateStats(city string, country string, countryCode string, httpsUpgrades int, adsBlocked int, hasSucceedingProxy bool) error {
log.Debugf("UpdateStats called with city %v and country %v and code %v", city, country, countryCode)
// Keep name as p1,p2,p3.....
// Name become part of Objective c so this is important
func (s *SessionModel) UpdateStats(p0 string, p1 string, p2 string, p3 int, p4 int, p5 bool) error {
log.Debugf("UpdateStats called with city %v and country %v and code %v", p0, p1, p2)
err := pathdb.Mutate(s.db, func(tx pathdb.TX) error {
pathdb.Put[string](tx, SERVER_COUNTRY, country, "")
pathdb.Put[string](tx, SERVER_CITY, city, "")
pathdb.Put[string](tx, SERVER_COUNTRY_CODE, countryCode, "")
pathdb.Put[bool](tx, HAS_SUCCEEDING_PROXY, hasSucceedingProxy, "")
pathdb.Put[string](tx, SERVER_COUNTRY, p1, "")
pathdb.Put[string](tx, SERVER_CITY, p0, "")
pathdb.Put[string](tx, SERVER_COUNTRY_CODE, p2, "")
pathdb.Put[bool](tx, HAS_SUCCEEDING_PROXY, p5, "")
// Not using ads blocked any more
return nil
})
Expand All @@ -313,10 +339,12 @@ func (s *SessionModel) SetStaging(stageing bool) error {
return nil
}

func (s *SessionModel) BandwidthUpdate(percent int, remaining int, allowed int) error {
log.Debugf("BandwidthUpdate percent %v remaining %v allowed %v", percent, remaining, allowed)
// Keep name as p1,p2,p3.....
// Name become part of Objective c so this is important
func (s *SessionModel) BandwidthUpdate(p1 int, p2 int, p3 int, p4 int) error {

err := pathdb.Mutate(s.db, func(tx pathdb.TX) error {
pathdb.Put[int](tx, LATEST_BANDWIDTH, percent, "")
pathdb.Put[int](tx, LATEST_BANDWIDTH, p1, "")
return nil
})
return err
Expand Down Expand Up @@ -610,12 +638,16 @@ func userCreate(m *baseModel, local string) error {
log.Errorf("Error decoding response body: %v", err)
return err
}
log.Debugf("Response from API after decode %v", userResponse)
//Save user refferal code
if userResponse.Referral != "" {
err := setReferalCode(m, userResponse.Referral)
return err
if err != nil {
return err
}
}
//Save user id and token
log.Debugf("Response from API %v", userResponse.UserID)
setUserIdAndToken(m, userResponse.UserID, userResponse.Token)
log.Debugf("Created new Lantern user: %+v", userResponse)
return nil
Expand Down
11 changes: 11 additions & 0 deletions internalsdk/utils.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package internalsdk

import (
"encoding/binary"
"encoding/json"
"fmt"
"math"
"reflect"

"github.com/getlantern/pathdb"
Expand Down Expand Up @@ -105,3 +108,11 @@ func convertValueToSupportedTypes(rawValue interface{}) interface{} {
}
return convertedValue
}

func BytesToFloat64LittleEndian(b []byte) (float64, error) {
if len(b) != 8 {
return 0, fmt.Errorf("expected 8 bytes but got %d", len(b))
}
bits := binary.LittleEndian.Uint64(b)
return math.Float64frombits(bits), nil
}
2 changes: 1 addition & 1 deletion ios/Runner/Lantern/Core/Vpn/VPNManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ class VPNManager: VPNBase {
let provider = NETunnelProviderManager()
let config = NETunnelProviderProtocol()
config.providerBundleIdentifier = Constants.netExBundleId
config.serverAddress = "0.0.0.0" // needs to be set but purely aesthetic
config.serverAddress = "0.0.0.0" // needs to be set but purely 8.8.8.8
provider.protocolConfiguration = config
provider.isEnabled = true // calling start when disabled crashes
// Set rules for onDemand...
Expand Down
12 changes: 2 additions & 10 deletions ios/Runner/Lantern/Core/Vpn/VpnHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,19 @@ class VpnHelper: NSObject {
notificationCenter: .default,
flashlightManager: FlashlightManager.appDefault,
vpnManager: ( VPNManager.appDefault))

// MARK: State
static let didUpdateStateNotification = Notification.Name("Lantern.didUpdateState")

enum VPNState: Equatable {
case configuring
case idle(Error?)
case connecting
case connected
case disconnecting

var isIdle: Bool {
if case .idle = self { return true }
return false
}
}

var configuring: Bool {
didSet {
guard oldValue != configuring else { return }
Expand All @@ -57,19 +53,16 @@ class VpnHelper: NSObject {
}

static let hasFetchedConfigDefaultsKey = "Lantern.hasConfig"

// Apple
let fileManager: FileManager
let userDefaults: UserDefaults
let notificationCenter: NotificationCenter

// Custom
let constants: Constants
let flashlightManager: FlashlightManager
let vpnManager: VPNBase
var configFetchTimer: Timer!
var hasConfiguredThisSession = false

var hasFetchedConfigOnce: Bool {
return (userDefaults.value(forKey: VpnHelper.hasFetchedConfigDefaultsKey) as? Bool) ?? false
}
Expand All @@ -82,14 +75,12 @@ class VpnHelper: NSObject {
vpnManager: VPNBase,
userNotificationsManager: UserNotificationsManager? = nil
) {

self.constants = constants
self.fileManager = fileManager
self.userDefaults = userDefaults
self.notificationCenter = notificationCenter
self.flashlightManager = flashlightManager
self.vpnManager = vpnManager

configuring = true
_state = .idle(nil)
super.init()
Expand Down Expand Up @@ -124,6 +115,7 @@ class VpnHelper: NSObject {
private func createFilesForAppGoPackage() {
// where "~" is the shared app group container...
// create process-specific directory @ ~/app

do {
try fileManager.ensureDirectoryExists(at: constants.targetDirectoryURL)
} catch {
Expand Down Expand Up @@ -258,7 +250,7 @@ class VpnHelper: NSObject {
self?.messageNetExToUpdateExcludedIPs()
}
self?.userDefaults.set(refreshProxies, forKey: VpnHelper.hasFetchedConfigDefaultsKey)
logger.debug("Successfully fetched new config")
logger.debug("Successfully fetched new config with \(result)")
completion(.success(()))
case .failure(let error):
// TODO: convert this error to a Lantern.Error
Expand Down
Loading

0 comments on commit ff593d0

Please sign in to comment.