Skip to content

Commit

Permalink
Show data cap after receiving first bandwidth update (#1241)
Browse files Browse the repository at this point in the history
* Updates to data cap

* update protobuf

* clean-ups

* Update logging

* Rename fields

* update session model
  • Loading branch information
atavism authored Dec 1, 2024
1 parent 481ee40 commit 021ecb7
Show file tree
Hide file tree
Showing 10 changed files with 293 additions and 255 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ protos: lib/features/vpn internalsdk/protos/vpn.pb.go
lib/messaging/protos_flutteronly/messaging.pb.dart: protos_flutteronly/messaging.proto
@protoc --dart_out=./lib/messaging --plugin=protoc-gen-dart=$$HOME/.pub-cache/bin/protoc-gen-dart protos_flutteronly/messaging.proto

lib/vpn/protos_shared/vpn.pb.dart: protos_shared/vpn.proto
@protoc --dart_out=./lib/vpn --plugin=protoc-gen-dart=$$HOME/.pub-cache/bin/protoc-gen-dart protos_shared/vpn.proto
lib/features/vpn/protos_shared/vpn.pb.dart: protos_shared/vpn.proto
@protoc --dart_out=./lib/features/vpn --plugin=protoc-gen-dart=$$HOME/.pub-cache/bin/protoc-gen-dart protos_shared/vpn.proto

internalsdk/protos/%.pb.go: protos_shared/%.proto
@echo "Generating Go protobuf for $<"
Expand Down
44 changes: 15 additions & 29 deletions desktop/datacap/datacap.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,24 @@ func ServeDataCap(channel ws.UIChannel, iconURL func() string, clickURL func() s
log.Errorf("Error registering with UI? %v", err)
return err
}
// dc := &dataCap{iconURL: iconURL, clickURL: clickURL, isPro: isPro}
go func() {
for quota := range bandwidth.Updates {
percent, remaining, allowed := getBandwidth(quota)
bandwidthMap := map[string]interface{}{
"percent": percent,
"remaining": remaining,
"allowed": allowed,
mibAllowed, mibUsed, percent := 0, 0, 0
if quota != nil {
mibUsed = int(quota.MiBUsed)
mibAllowed = int(quota.MiBAllowed)
if quota.MiBUsed >= quota.MiBAllowed {
percent = 100
} else {
percent = int(100 * (float64(quota.MiBUsed) / float64(quota.MiBAllowed)))
}
}

bservice.Out <- map[string]interface{}{
"percent": percent,
"mibUsed": mibUsed,
"mibAllowed": mibAllowed,
}
bservice.Out <- bandwidthMap
// dc.processQuota(bservice.Out, quota)
}
}()
return nil
Expand Down Expand Up @@ -99,27 +106,6 @@ func (dc *dataCap) processQuota(out chan<- interface{}, quota *bandwidth.Quota)
})
}
}
func getBandwidth(quota *bandwidth.Quota) (int, int, int) {
remaining := 0
percent := 100
if quota == nil {
return 0, 0, 0
}

allowed := quota.MiBAllowed
if allowed > 50000000 {
return 0, 0, 0
}

if quota.MiBUsed >= quota.MiBAllowed {
percent = 100
remaining = 0
} else {
percent = int(100 * (float64(quota.MiBUsed) / float64(quota.MiBAllowed)))
remaining = int(quota.MiBAllowed - quota.MiBUsed)
}
return percent, remaining, int(quota.MiBAllowed)
}

// AddDataCapListener adds a listener for any updates to the data cap.
func AddDataCapListener(l func(hitDataCap bool)) {
Expand Down
348 changes: 174 additions & 174 deletions internalsdk/protos/vpn.pb.go

Large diffs are not rendered by default.

14 changes: 7 additions & 7 deletions internalsdk/session_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -500,10 +500,10 @@ func (m *SessionModel) doInvokeMethod(method string, arguments Arguments) (inter
return true, nil
case "updateBandwidth":
percent := arguments.Get("percent").Int()
remaining := arguments.Get("remaining").Int()
allowed := arguments.Get("allowed").Int()
mibUsed := arguments.Get("mibUsed").Int()
mibAllowed := arguments.Get("mibAllowed").Int()
ttlSeconds := arguments.Get("ttlSeconds").Int()
err := m.BandwidthUpdate(percent, remaining, allowed, ttlSeconds)
err := m.BandwidthUpdate(percent, mibUsed, mibAllowed, ttlSeconds)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -947,15 +947,15 @@ func (m *SessionModel) SetStaging(staging bool) error {
return nil
}

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

bandwidth := &protos.Bandwidth{
Percent: int64(p1),
Remaining: int64(p2),
Allowed: int64(p3),
MibUsed: int64(p2),
MibAllowed: int64(p3),
TtlSeconds: int64(p4),
}
return pathdb.Mutate(m.db, func(tx pathdb.TX) error {
Expand Down
6 changes: 3 additions & 3 deletions internalsdk/vpn_model.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,12 +101,12 @@ func (m *VPNModel) SaveVPNStatus(status string) error {
})
}

func (m *VPNModel) UpdateBandwidth(percent int64, remaining int64, allowedint int64, ttlSeconds int64) error {
func (m *VPNModel) UpdateBandwidth(percent int64, mibUsed int64, mibAllowed int64, ttlSeconds int64) error {
return pathdb.Mutate(m.db, func(tx pathdb.TX) error {
bandwidth := &protos.Bandwidth{
Percent: percent,
Remaining: remaining,
Allowed: allowedint,
MibUsed: mibUsed,
MibAllowed: mibAllowed,
TtlSeconds: ttlSeconds,
}
return pathdb.Put(tx, pathBandwidth, bandwidth, "")
Expand Down
14 changes: 4 additions & 10 deletions lib/core/service/websocket_subscriber.dart
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ class WebsocketSubscriber {
});
}
case _WebsocketMessageType.pro:
_webSocketLogger.i("Websocket message[Pro]: $json");
_webSocketLogger.i("Websocket message[Pro]: $message");
final userStatus = message['userStatus'];
final userLevel = message['userLevel'];
final deviceLinkingCode = message['deviceLinkingCode'];
Expand All @@ -108,16 +108,11 @@ class WebsocketSubscriber {
}

case _WebsocketMessageType.bandwidth:
_webSocketLogger.i("Websocket message[Bandwidth]: $json");
final Map res = jsonDecode(jsonEncode(message));
_webSocketLogger.i("Websocket message[Bandwidth]: $message");
sessionModel.bandwidthNotifier.value = Bandwidth.create()
..mergeFromProto3Json({
'allowed': res['allowed'],
'remaining': res['remaining'],
'percent': res['percent'],
});
..mergeFromProto3Json(message);
case _WebsocketMessageType.config:
_webSocketLogger.i("Websocket message[config]: $json");
_webSocketLogger.i("Websocket message[config]: $message");
final ConfigOptions config = ConfigOptions.fromJson(message);

sessionModel.isAuthEnabled.value = config.authEnabled;
Expand All @@ -142,7 +137,6 @@ class WebsocketSubscriber {
}
}


/// Method to update plans
void _updatePlans(Map<String, Plan>? plans) {
if (plans != null) {
Expand Down
76 changes: 60 additions & 16 deletions lib/features/vpn/protos_shared/vpn.pb.dart
Original file line number Diff line number Diff line change
Expand Up @@ -95,19 +95,19 @@ class ServerInfo extends $pb.GeneratedMessage {
class Bandwidth extends $pb.GeneratedMessage {
factory Bandwidth({
$fixnum.Int64? percent,
$fixnum.Int64? remaining,
$fixnum.Int64? allowed,
$fixnum.Int64? mibUsed,
$fixnum.Int64? mibAllowed,
$fixnum.Int64? ttlSeconds,
}) {
final $result = create();
if (percent != null) {
$result.percent = percent;
}
if (remaining != null) {
$result.remaining = remaining;
if (mibUsed != null) {
$result.mibUsed = mibUsed;
}
if (allowed != null) {
$result.allowed = allowed;
if (mibAllowed != null) {
$result.mibAllowed = mibAllowed;
}
if (ttlSeconds != null) {
$result.ttlSeconds = ttlSeconds;
Expand All @@ -120,8 +120,8 @@ class Bandwidth extends $pb.GeneratedMessage {

static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'Bandwidth', createEmptyInstance: create)
..aInt64(1, _omitFieldNames ? '' : 'percent')
..aInt64(2, _omitFieldNames ? '' : 'remaining')
..aInt64(3, _omitFieldNames ? '' : 'allowed')
..aInt64(2, _omitFieldNames ? '' : 'mibUsed', protoName: 'mibUsed')
..aInt64(3, _omitFieldNames ? '' : 'mibAllowed', protoName: 'mibAllowed')
..aInt64(4, _omitFieldNames ? '' : 'ttlSeconds', protoName: 'ttlSeconds')
..hasRequiredFields = false
;
Expand Down Expand Up @@ -157,22 +157,22 @@ class Bandwidth extends $pb.GeneratedMessage {
void clearPercent() => clearField(1);

@$pb.TagNumber(2)
$fixnum.Int64 get remaining => $_getI64(1);
$fixnum.Int64 get mibUsed => $_getI64(1);
@$pb.TagNumber(2)
set remaining($fixnum.Int64 v) { $_setInt64(1, v); }
set mibUsed($fixnum.Int64 v) { $_setInt64(1, v); }
@$pb.TagNumber(2)
$core.bool hasRemaining() => $_has(1);
$core.bool hasMibUsed() => $_has(1);
@$pb.TagNumber(2)
void clearRemaining() => clearField(2);
void clearMibUsed() => clearField(2);

@$pb.TagNumber(3)
$fixnum.Int64 get allowed => $_getI64(2);
$fixnum.Int64 get mibAllowed => $_getI64(2);
@$pb.TagNumber(3)
set allowed($fixnum.Int64 v) { $_setInt64(2, v); }
set mibAllowed($fixnum.Int64 v) { $_setInt64(2, v); }
@$pb.TagNumber(3)
$core.bool hasAllowed() => $_has(2);
$core.bool hasMibAllowed() => $_has(2);
@$pb.TagNumber(3)
void clearAllowed() => clearField(3);
void clearMibAllowed() => clearField(3);

@$pb.TagNumber(4)
$fixnum.Int64 get ttlSeconds => $_getI64(3);
Expand Down Expand Up @@ -276,6 +276,50 @@ class AppData extends $pb.GeneratedMessage {
void clearAllowedAccess() => clearField(4);
}

class AppsData extends $pb.GeneratedMessage {
factory AppsData({
$core.Iterable<AppData>? appsList,
}) {
final $result = create();
if (appsList != null) {
$result.appsList.addAll(appsList);
}
return $result;
}
AppsData._() : super();
factory AppsData.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
factory AppsData.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);

static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'AppsData', createEmptyInstance: create)
..pc<AppData>(1, _omitFieldNames ? '' : 'appsList', $pb.PbFieldType.PM, protoName: 'appsList', subBuilder: AppData.create)
..hasRequiredFields = false
;

@$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
AppsData clone() => AppsData()..mergeFromMessage(this);
@$core.Deprecated(
'Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
AppsData copyWith(void Function(AppsData) updates) => super.copyWith((message) => updates(message as AppsData)) as AppsData;

$pb.BuilderInfo get info_ => _i;

@$core.pragma('dart2js:noInline')
static AppsData create() => AppsData._();
AppsData createEmptyInstance() => create();
static $pb.PbList<AppsData> createRepeated() => $pb.PbList<AppsData>();
@$core.pragma('dart2js:noInline')
static AppsData getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<AppsData>(create);
static AppsData? _defaultInstance;

@$pb.TagNumber(1)
$core.List<AppData> get appsList => $_getList(0);
}

class Device extends $pb.GeneratedMessage {
factory Device({
$core.String? id,
Expand Down
22 changes: 17 additions & 5 deletions lib/features/vpn/protos_shared/vpn.pbjson.dart
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,17 @@ const Bandwidth$json = {
'1': 'Bandwidth',
'2': [
{'1': 'percent', '3': 1, '4': 1, '5': 3, '10': 'percent'},
{'1': 'remaining', '3': 2, '4': 1, '5': 3, '10': 'remaining'},
{'1': 'allowed', '3': 3, '4': 1, '5': 3, '10': 'allowed'},
{'1': 'mibUsed', '3': 2, '4': 1, '5': 3, '10': 'mibUsed'},
{'1': 'mibAllowed', '3': 3, '4': 1, '5': 3, '10': 'mibAllowed'},
{'1': 'ttlSeconds', '3': 4, '4': 1, '5': 3, '10': 'ttlSeconds'},
],
};

/// Descriptor for `Bandwidth`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List bandwidthDescriptor = $convert.base64Decode(
'CglCYW5kd2lkdGgSGAoHcGVyY2VudBgBIAEoA1IHcGVyY2VudBIcCglyZW1haW5pbmcYAiABKA'
'NSCXJlbWFpbmluZxIYCgdhbGxvd2VkGAMgASgDUgdhbGxvd2VkEh4KCnR0bFNlY29uZHMYBCAB'
'KANSCnR0bFNlY29uZHM=');
'CglCYW5kd2lkdGgSGAoHcGVyY2VudBgBIAEoA1IHcGVyY2VudBIYCgdtaWJVc2VkGAIgASgDUg'
'dtaWJVc2VkEh4KCm1pYkFsbG93ZWQYAyABKANSCm1pYkFsbG93ZWQSHgoKdHRsU2Vjb25kcxgE'
'IAEoA1IKdHRsU2Vjb25kcw==');

@$core.Deprecated('Use appDataDescriptor instead')
const AppData$json = {
Expand All @@ -62,6 +62,18 @@ final $typed_data.Uint8List appDataDescriptor = $convert.base64Decode(
'gJUgRuYW1lEhIKBGljb24YAyABKAxSBGljb24SJAoNYWxsb3dlZEFjY2VzcxgEIAEoCFINYWxs'
'b3dlZEFjY2Vzcw==');

@$core.Deprecated('Use appsDataDescriptor instead')
const AppsData$json = {
'1': 'AppsData',
'2': [
{'1': 'appsList', '3': 1, '4': 3, '5': 11, '6': '.AppData', '10': 'appsList'},
],
};

/// Descriptor for `AppsData`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List appsDataDescriptor = $convert.base64Decode(
'CghBcHBzRGF0YRIkCghhcHBzTGlzdBgBIAMoCzIILkFwcERhdGFSCGFwcHNMaXN0');

@$core.Deprecated('Use deviceDescriptor instead')
const Device$json = {
'1': 'Device',
Expand Down
16 changes: 9 additions & 7 deletions lib/features/vpn/vpn_bandwidth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ class VPNBandwidth extends StatelessWidget {
@override
Widget build(BuildContext context) {
return sessionModel
.bandwidth((BuildContext context, Bandwidth bandwidth, Widget? child) {
// User does not have bandwidth cap off
if (bandwidth.remaining > 0 ) {
.bandwidth((BuildContext context, Bandwidth? bandwidth, Widget? child) {
return sessionModel.proUser((context, isProUser, child) {
if (bandwidth == null || isProUser) {
// Always disable the data cap if it's a pro user or we haven't
// received any bandwidth updates
return const SizedBox();
}
return Column(
children: [
Container(
Expand All @@ -30,7 +34,7 @@ class VPNBandwidth extends StatelessWidget {
),
Expanded(
child: CText(
'${bandwidth.remaining}/${bandwidth.allowed} MB',
'${bandwidth.mibUsed}/${bandwidth.mibAllowed} MB',
textAlign: TextAlign.end,
style: tsSubtitle4,
),
Expand Down Expand Up @@ -60,9 +64,7 @@ class VPNBandwidth extends StatelessWidget {
),
],
);
} else {
return const SizedBox();
}
});
});
}
}
4 changes: 2 additions & 2 deletions protos_shared/vpn.proto
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ message ServerInfo {

message Bandwidth {
int64 percent = 1; // [0, 100]
int64 remaining = 2; // in MB
int64 allowed = 3; // in MB
int64 mibUsed = 2; // in MB
int64 mibAllowed = 3; // in MB
int64 ttlSeconds = 4; // number of seconds left before data reset
}

Expand Down

0 comments on commit 021ecb7

Please sign in to comment.