Skip to content

Commit

Permalink
- Using the native implementation that doesn't require the requests l…
Browse files Browse the repository at this point in the history
…ibrary.

- Add WebUI support.
- Fix some pylint functional issues.
- Update project to use setup.py through the debugger.
  • Loading branch information
Lee authored and Lee committed Dec 9, 2016
1 parent e7f4a2c commit ec58b08
Show file tree
Hide file tree
Showing 9 changed files with 167 additions and 72 deletions.
8 changes: 7 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.

# Deluge pyegg build folders
build/
dist/
*.egg-info/

# User-specific files
*.suo
*.user
Expand Down Expand Up @@ -186,4 +191,5 @@ FakesAssemblies/
# LightSwitch generated files
GeneratedArtifacts/
_Pvt_Extensions/
ModelManifest.xml
ModelManifest.xml
/.vs/config/applicationhost.config
1 change: 1 addition & 0 deletions PIAPortForward.pyproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
<InterpreterId />
<InterpreterVersion />
<EnableNativeCodeDebugging>False</EnableNativeCodeDebugging>
<CommandLineArguments>bdist_egg</CommandLineArguments>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'" />
<PropertyGroup Condition="'$(Configuration)' == 'Release'" />
Expand Down
44 changes: 26 additions & 18 deletions piaportforward/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,21 @@
import pia_port

DEFAULT_PREFS = {
'pia_username':'',
'pia_password':'',
'pia_username': '',
'pia_password': '',
}


class Core(CorePluginBase):
def __init__(self):
self.successfully_acquired_port = False
self.pia_username = ''
self.pia_password = ''

def enable(self):
log.info( 'Enabling' )
self.config = deluge.configmanager.ConfigManager('piaportforward.conf', DEFAULT_PREFS)
log.info('Enabling')
self.config = deluge.configmanager.ConfigManager(
'piaportforward.conf', DEFAULT_PREFS)
self.pia_username = self.config['pia_username']
self.pia_password = self.config['pia_password']
self.pia_client_id = pia_port.generate_client_id()
Expand All @@ -70,7 +77,7 @@ def enable(self):
self.update_status_slow_timer.start(time_in_sec_interval)

def disable(self):
log.info( 'Disabling' )
log.info('Disabling')
self.update_status_fast_timer.stop()
self.update_status_slow_timer.stop()

Expand All @@ -82,54 +89,55 @@ def update(self):

def slow_check(self):
if self.successfully_acquired_port:
log.info( 'Slow port refresh' )
log.info('Slow port refresh')
self.refresh_connection()

def fast_check(self):
if not self.successfully_acquired_port:
log.info( 'Fast port refresh' )
log.info('Fast port refresh')
self.refresh_connection()

def refresh_connection(self):
log.info( 'Refreshing listening port...' )
log.info('Refreshing listening port...')
local_ip = pia_port.get_active_local_ip()
if not local_ip.startswith('10.'):
log.info( 'Not a VPN local IP' )
log.info('Not a VPN local IP')
return

core = component.get('Core')
previous_listen_port = core.get_listen_port()
log.info( 'Current listening port: {}'.format(previous_listen_port) )
log.info('Current listening port: {}'.format(previous_listen_port))

def acquire_port( is_open ):
def acquire_port(is_open):
''' Callback after test_listen_port is complete '''
if is_open:
log.info( 'port is open' )
log.info('port is open')
self.successfully_acquired_port = True
return

log.info( 'port is not open' )
log.info('port is not open')
self.successfully_acquired_port = False
self.pia_username = self.config['pia_username']
self.pia_password = self.config['pia_password']
new_port = pia_port.acquire_port(self.pia_username,
self.pia_password,
self.pia_client_id,
local_ip,
log.info )
log.info)
if new_port is None:
log.info( 'Failed to acquire port' )
log.info('Failed to acquire port')
return

if new_port == previous_listen_port:
log.info( 'Something wrong with the port forward. Same port as the previous.' )
log.info(
'Something wrong with the port forward. Same port as the previous.')
return

core.set_config({'random_port': False})
core.set_config({'listen_ports': [new_port, new_port]})
log.info( 'Config successfully changed' )
log.info('Config successfully changed')

core.test_listen_port().addCallback( acquire_port )
core.test_listen_port().addCallback(acquire_port)

@export
def set_config(self, config):
Expand Down
95 changes: 83 additions & 12 deletions piaportforward/data/piaportforward.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,20 +31,91 @@ Copyright:
statement from all source files in the program, then also delete it here.
*/

PIAPortForwardPlugin = Ext.extend(Deluge.Plugin, {
constructor: function(config) {
config = Ext.apply({
name: "PIAPortForward"
}, config);
PIAPortForwardPlugin.superclass.constructor.call(this, config);
},
Ext.ns('Deluge.ux.preferences');

onDisable: function() {
/**
* @class Deluge.ux.preferences.PIAPortForwardPage
* @extends Ext.Panel
*/
Deluge.ux.preferences.PIAPortForwardPage = Ext.extend(Ext.Panel, {

},
title: _('PIAPortForward'),
layout: 'fit',
border: false,

onEnable: function() {
initComponent: function () {
Deluge.ux.preferences.PIAPortForwardPage.superclass.initComponent.call(this);

}
this.form = this.add({
xtype: 'form',
layout: 'form',
border: false,
autoHeight: true
});

fieldset = this.form.add({
xtype: 'fieldset',
border: false,
title: '',
autoHeight: true,
labelAlign: 'top',
labelWidth: 80,
defaultType: 'textfield'
});

this.username = fieldset.add({
fieldLabel: _('Username:'),
labelSeparator: '',
name: 'username',
width: '97%'
});

this.password = fieldset.add({
fieldLabel: _('Password:'),
labelSeparator: '',
name: 'password',
width: '97%'
});

this.on('show', this.updateConfig, this);
},

onApply: function () {
// build settings object
var config = {}

config['pia_username'] = this.username.getValue();
config['pia_password'] = this.password.getValue();

deluge.client.piaportforward.set_config(config);
},

onOk: function () {
this.onApply();
},

updateConfig: function () {
deluge.client.piaportforward.get_config({
success: function (config) {
this.username.setValue(config['pia_username']);
this.password.setValue(config['pia_password']);
},
scope: this
});
}
});


Deluge.plugins.PIAPortForwardPlugin = Ext.extend(Deluge.Plugin, {

name: 'PIAPortForward',

onDisable: function () {
deluge.preferences.removePage(this.prefsPage);
},

onEnable: function () {
this.prefsPage = deluge.preferences.addPage(new Deluge.ux.preferences.PIAPortForwardPage());
}
});
new PIAPortForwardPlugin();
Deluge.registerPlugin('PIAPortForward', Deluge.plugins.PIAPortForwardPlugin);
36 changes: 20 additions & 16 deletions piaportforward/pia_port.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import httplib
import json
import random
import requests
import socket
import string
import urllib

PIA_SERVER = 'www.privateinternetaccess.com'


def get_active_local_ip():
# Get active local IP
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Expand All @@ -14,34 +17,35 @@ def get_active_local_ip():
finally:
tcp_socket.close()


def generate_client_id():
# Generate client ID
return ''.join( random.choice(string.hexdigits) for char in xrange(32) ).lower()
return ''.join(random.choice(string.hexdigits) for char in xrange(32)).lower()


def acquire_port( user_name, password, client_id, local_ip, log ):
def acquire_port(user_name, password, client_id, local_ip, log):
# Set up parameters
values = {'user':user_name,
'pass':password,
'client_id':client_id,
'local_ip':local_ip}
values = urllib.urlencode({'user': user_name,
'pass': password,
'client_id': client_id,
'local_ip': local_ip})

# Send request
try:
response = requests.post('https://' + PIA_SERVER + '/vpninfo/port_forward_assignment', params=values)
except requests.exceptions.RequestException as request_exception:
log( request_exception.message )
return
connection = httplib.HTTPSConnection(PIA_SERVER)
connection.request('POST', '/vpninfo/port_forward_assignment', values)
response = connection.getresponse()

# Process response
status_code_ok = 200
if response.status_code != status_code_ok:
log( '{}: '.format(response.status_code) + response.reason )
if response.status != status_code_ok:
log('{}: '.format(response.status) + response.reason)
return

data = response.json()
# Extract port from json data
data = json.load(response)

if 'port' not in data:
log( data['error'] )
log(data['error'])
return

return data['port']
19 changes: 11 additions & 8 deletions piaportforward/pia_port_native.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

PIA_SERVER = 'www.privateinternetaccess.com'


def get_active_local_ip():
# Get active local IP
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
Expand All @@ -16,16 +17,18 @@ def get_active_local_ip():
finally:
tcp_socket.close()


def generate_client_id():
# Generate client ID
return ''.join( random.choice(string.hexdigits) for char in xrange(32) ).lower()
return ''.join(random.choice(string.hexdigits) for char in xrange(32)).lower()


def acquire_port( user_name, password, client_id, local_ip, log ):
def acquire_port(user_name, password, client_id, local_ip, log):
# Set up parameters
values = urllib.urlencode({'user':user_name,
'pass':password,
'client_id':client_id,
'local_ip':local_ip})
values = urllib.urlencode({'user': user_name,
'pass': password,
'client_id': client_id,
'local_ip': local_ip})

# Send request
connection = httplib.HTTPSConnection(PIA_SERVER)
Expand All @@ -35,14 +38,14 @@ def acquire_port( user_name, password, client_id, local_ip, log ):
# Process response
status_code_ok = 200
if response.status != status_code_ok:
log( '{}: '.format(response.status) + response.reason )
log('{}: '.format(response.status) + response.reason)
return

# Extract port from json data
data = json.load(response)

if 'port' not in data:
log( data['error'] )
log(data['error'])
return

return data['port']
Loading

0 comments on commit ec58b08

Please sign in to comment.