adsAutoSwitcher – Appcelerator Titanium script to rotate Admob and iAds on iOS applications
Ads-auto-switcher-for-Titanium
adsAutoSwitcher.js is a (commonJS) script that allow you to use both iAds and Admob at the same place within a ©Titanium iOS project. It works with ti.admob module(1.3) : With this script, per default, Admob is always shown, while iAds is shown (on top of admob) and hidden during some seconds. I made it to simplify my life when i need to manage ads within my applications The script manages to move and/or to resize an UI object when ads are visible. Be carefull with admob when closing a window. The module ti.admob is not really good to stop a refreshing admob..
adsAutoSwitcher.js is freely available on gitbub
[updated 2012/25/11] New major version ! adsAutoSwitcher V2. The updated V2 changelog is :
- Rewrite and simplification for ads.js, renammed as adsAutoSwitcher
- Compatible with Ti SDK > 2
- commonJS archi
- And really so much easier to use now!!
How To use :
This adsAutoSwitcher prints the ads on top of a tableview object by moving it down The ads are delayed of 2sec
Before : tableview top = 0, height = 200
After : top = 50, height = 200
-
-
var myAds = require ('modules/adsAutoSwither');
-
var ads = new myAds();
-
ads.setAdmobPublisherId('myAdmobKey');
-
ads.setIadsShowHide('iAdsShowHide.Window');
-
ads.setGlobalDelayStart(2000);
-
ads.showAdvert(tableView,'move','top');
Same as before, but now, the tableview is resized from its top
Before : tableview top = 0, height = 200
After : top = 50, height = 150
-
[...]
-
ads.showAdvert(tableView,'resize','top');
Same as before, but now, the tableview is resized from its bottom
Before : tableview top = 0, height = 200.
After : top = 0, height = 150, so bottom is now 150
-
[...]
-
ads.showAdvert(tableView,'resize','bottom');
Fixed banner at top = 120. No UI object resized or moved
-
[...]
-
ads.setAdsTopInit(120);
-
ads.showAdvert(tableView,'','');
Full script for adsAutoSwitcher.js 2.0.008
-
-
Titanium.Admob = Ti.Admob;
-
-
function AdsAutoSwither() {
-
/**
-
* Single contexte name of window
-
* Only use it if your application is a single context application. Then set here the instance of your window
-
*/
-
var _singleContextWin = null;
-
this.setSingleContextWin = function(name) {
-
_singleContextWin = name;
-
};
-
-
/**
-
* Delay in ms before calling the ads
-
*/
-
var _globalDelayStart = 0;
-
this.setGlobalDelayStart = function(ms) {
-
_globalDelayStart = ms;
-
};
-
-
/**
-
* Top margin (px) for the object to move
-
*/
-
var _objMargin = 0;
-
this.setObjMargin = function(px){
-
_objMargin = px;
-
};
-
-
/**
-
* To enabled or not admob. Don't forget to change ads.iadsStartDelay if no admob
-
*/
-
var _useAdmob = true;
-
this.setUseAdmob = function(b) {
-
_useAdmob = b;
-
};
-
-
/**
-
* To enabled or not iAds.
-
*/
-
var _useIads = true;
-
this.setUseIads = function(b) {
-
_useIads = b;
-
};
-
-
/**
-
* Milliseconds before starting iads
-
*/
-
var _iadsStartDelay = 30000;
-
this.setIadsStartDelay = function(ms) {
-
_iadsStartDelay = ms;
-
};
-
-
/**
-
* Initial top position for the ads banners
-
* Set it to Ti.Platform.displayCaps.platformHeight + 50 for a bottom ad
-
*/
-
var _adsTopInit = -50;
-
this.setAdsTopInit = function(px) {
-
_adsTopInit = px;
-
};
-
-
/**
-
* The event's name to be fired. It's recommanded to use one per ads's instance.
-
*/
-
var _iAdsShowHide = 'iAdsShowHide';
-
this.setIadsShowHide = function(str) {
-
_iAdsShowHide = str;
-
};
-
-
/**
-
* Required : your admob id
-
*/
-
var _admobPublisherId = null;
-
this.setAdmobPublisherId = function(str) {
-
_admobPublisherId = str;
-
};
-
-
// -- Admob extra public parameters -- //
-
/**
-
* Date of birth, to better target the ads, new Date(1985, 10, 1, 12, 1, 1)
-
*/
-
this.adDateOfBirth = '';
-
-
/**
-
* Gender 'male' or 'female'
-
*/
-
this.adGender = '';
-
-
/**
-
* Keywords about the ads to print
-
*/
-
this.adKeywords = '';
-
-
/**
-
* Test mode for admob
-
*/
-
this.adTesting = false;
-
-
/**
-
* admob's backgroundColor
-
*/
-
this.adBackgroundColor = "#FDFEFD";
-
-
// -- iAds extra public parameters -- //
-
/**
-
* iAds's border color
-
*/
-
this.iAdsBorderColor = '#FDFEFD';
-
-
/**
-
* iAds's backgroundColor
-
*/
-
this.iAdsBackgroundColor = '#FDFEFD';
-
-
/**
-
* How long iAd stay visible (milliseconds)
-
*/
-
this.iAdsTimeToShow = 15000;
-
-
/**
-
* How long iAd is hidden (milliseconds)
-
*/
-
this.iAdsTimeToHide = 30000;
-
-
/**
-
* Public methods to expose the actual iAds/Admob visibility
-
*/
-
var _iAdsVisible = false;
-
this.getIadsVisible = function() {
-
return _iAdsVisible;
-
};
-
var _adMobVisible = false;
-
this.getAdMobVisible = function() {
-
return _adMobVisible;
-
};
-
-
// -- Private members -- //
-
/**
-
* The UI object to be moved/resized when an ad is visible
-
*/
-
var _objUI = {};
-
-
/**
-
* The type of transformation for the object, can be : 'move' or 'resize' or '' (empty for fixed banner)
-
*/
-
var _alterFrom = '';
-
-
/**
-
* From where the object transformation should start : 'top' or 'bottom'
-
*/
-
var _alterType = '';
-
-
/**
-
* Top, bottom and height for the objUI
-
*/
-
var _objUIinitTop, _objUIinitBottom, _objUIinitHeight;
-
-
var _admob = null;
-
// ----------------------------------------------------------------------------
-
-
// ----------------------------------------------------------------------------
-
// ----------------------------------------------------------------------------
-
var _hideExtraAdsSpace = function() {
-
if (_alterType === 'move') {
-
if (_alterFrom === 'top') {
-
_objUI.animate({top:_objUIinitTop+ _objMargin,duration:250});
-
}
-
else { // TO CHECK ( - adsmargin?)
-
_objUI.animate({bottom:_objUIinitBottom+ _objMargin,duration:250});
-
}
-
} else {
-
if (_alterFrom === 'top') {
-
_objUI.animate({height:_objUIinitHeight,top:_objUIinitTop,duration:250});
-
}
-
else {
-
_objUI.animate({height:_objUIinitHeight,bottom:_objUIinitBottom,duration:250});
-
}
-
}
-
};
-
// ----------------------------------------------------------------------------
-
-
// ----------------------------------------------------------------------------
-
var _buildIads = function() {
-
var firstRun = true;
-
if (parseFloat(Titanium.Platform.version) >= 3.2) {
-
Ti.API.info('ads.showiAds - build iads');
-
var _iads = Ti.UI.iOS.createAdView({
-
width: Ti.UI.SIZE || 'auto',
-
height: Ti.UI.SIZE || 'auto',
-
top: _adsTopInit,
-
borderColor: this.iAdsBorderColor,
-
backgroundColor: this.iAdsBackgroundColor
-
});
-
_iads.addEventListener('load', function(){
-
Ti.API.info("ads.showiAds - iads loaded. First Run ? :"+firstRun);
-
_iAdsVisible = true;
-
if (firstRun) {
-
Ti.API.info("ads.showiAds - First iAds run : True");
-
firstRun = false;
-
}
-
else {
-
Ti.API.info("ads.showiAds - First iAds run ? : False");
-
}
-
timer=setInterval(_showIads, this.iAdsTimeToShow);
-
});
-
_iads.addEventListener('error', function(e){
-
Ti.API.info("ads.showiAds - iads error :"+e.message+ " --- adMobVisible="+_adMobVisible);
-
if (_iAdsVisible && _alterType != '') {
-
if (_adMobVisible) {
-
if (_alterType === 'move') {
-
if (_alterFrom === 'top') {
-
_objUI.animate({top:_objUIinitTop+50+_objMargin,duration:250});
-
}
-
else { // TO CHECK ( - adsmargin?)
-
_objUI.animate({bottom:_objUIinitBottom+50+ _objMargin,duration:250});
-
}
-
} else {
-
if (_alterFrom === 'top') {
-
_objUI.animate({height:_objUIinitHeight-50,top:_objUIinitTop+50+_objMargin,duration:250});
-
}
-
else {
-
_objUI.animate({height:_objUIinitHeight-50,bottom:_objUIinitBottom-53,duration:250});
-
}
-
}
-
-
} else { // hide the extra space for ads
-
_hideExtraAdsSpace();
-
}
-
}
-
_iads.top = _adsTopInit;
-
_iAdsVisible = false;
-
});
-
try {
-
Titanium.UI.currentWindow.add(_iads);
-
}
-
catch (e) {
-
_singleContextWin.add(_iads);
-
}
-
}
-
};
-
// ----------------------------------------------------------------------------
-
-
// ----------------------------------------------------------------------------
-
var _showIads = function() {
-
Ti.API.info("ads.showiAds - Receive iAdsShowHide. ads.iAdsVisible :"+_iAdsVisible + " -- iads.visible: "+_iads.visible+ " -- ads.adMobVisible: "+_adMobVisible);
-
if (_iAdsVisible && _iads.visible) {
-
if (_adMobVisible === false) {
-
// if admob's not visible, let iAds on screen
-
}
-
else { // to hide iAds
-
_iads.animate({top:_adsTopInit, duration:500}, function() { _iads.hide(); Ti.API.info("ads.showiAds - hide iads"); });
-
}
-
}
-
else { // to show iAds
-
if (_adMobVisible === false && _alterType != '') {
-
if (_alterType === 'move') {
-
if (_alterFrom === 'top') {
-
_objUI.animate({top:_objUIinitTop+50+_objMargin,duration:250});
-
}
-
else { // TO CHECK ( - adsmargin?)
-
_objUI.animate({bottom:_objUIinitBottom+50+ _objMargin,duration:250});
-
}
-
} else {
-
if (_alterFrom === 'top') {
-
_objUI.animate({height:_objUIinitHeight-50,top:_objUIinitTop+50+_objMargin,duration:250});
-
}
-
else {
-
_objUI.animate({height:_objUIinitHeight-58,bottom:_objUIinitBottom-58,duration:250});
-
}
-
}
-
}
-
_iads.show();
-
Ti.API.info("ads.showiAds - iads show");
-
if (_alterFrom === 'top') {
-
_iads.animate({top:_objUIinitTop,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
-
} else if (_alterFrom === 'bottom') {
-
_iads.animate({top:_objUIinitBottom-54,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
-
}
-
}
-
};
-
// ----------------------------------------------------------------------------
-
-
// ----------------------------------------------------------------------------
-
var _buildAdmob = function() {
-
if (_admob === null) {
-
Ti.API.info("ads.buildAdmob - try buildAdmob - ");
-
_admob = Ti.Admob.createView({
-
publisherId: _admobPublisherId, // required
-
top: _adsTopInit,
-
left: 0,
-
width: Ti.Platform.displayCaps.getPlatformWidth(), //320, // required
-
height: 50, // required
-
testing: this.adTesting,
-
adBackgroundColor: this.adBackgroundColor,
-
dateOfBirth: this.adDateOfBirth, //new Date(1985, 10, 1, 12, 1, 1),
-
gender: this.adGender, //'male',
-
keywords: this.adKeywords, //'',
-
refreshAd:15.0 //not working with actual ti.admob module (1.3), set refresh time within admob site
-
});
-
_admob.addEventListener('didFailToReceiveAd', function() {
-
_admob.top = _adsTopInit;
-
_admob = null;
-
if (!_iAdsVisible && _alterType != '') {
-
_hideExtraAdsSpace();
-
}
-
_adMobVisible = false;
-
setTimeout(_buildAdmob, 10000);
-
Ti.API.info("ads.buildAdmob - admob error : didFailToReceiveAd. Retry in 10s. adMobVisible:"+_adMobVisible);
-
});
-
_admob.addEventListener('didReceiveAd', function() {
-
Ti.API.info("ads.buildAdmob - admob event : didReceiveAd");
-
_showAdmob();
-
});
-
try {
-
Titanium.UI.currentWindow.add(_admob);
-
}
-
catch (e) {
-
_singleContextWin.add(_admob);
-
}
-
}
-
};
-
// ----------------------------------------------------------------------------
-
-
// ----------------------------------------------------------------------------
-
var _showAdmob = function() {
-
if (_adMobVisible === false) {
-
try {
-
if (!_iAdsVisible && _alterType != '') {
-
if (_alterType === 'move') {
-
if (_alterFrom === 'top') {
-
_objUI.animate({top:_objUIinitTop+50+_objMargin,duration:250});
-
}
-
else { // TO CHECK ( - adsmargin?)
-
_objUI.animate({bottom:_objUIinitBottom+50+ _objMargin,duration:250});
-
}
-
} else {
-
if (_alterFrom === 'top') {
-
_objUI.animate({height:_objUIinitHeight-50,top:_objUIinitTop+50+_objMargin,duration:250});
-
}
-
else {
-
_objUI.animate({height:_objUIinitHeight-58,bottom:_objUIinitBottom-58,duration:250});
-
}
-
}
-
}
-
_adMobVisible = true;
-
if (_alterFrom === 'top') {
-
_admob.animate({top:_objUIinitTop,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
-
} else if (_alterFrom === 'bottom') {
-
_admob.animate({top:_objUIinitBottom-58,duration:500,curve:Ti.UI.ANIMATION_CURVE_EASE_IN_OUT});
-
}
-
}
-
catch (e) {
-
_adMobVisible = false;
-
Ti.API.info("ads.showAdmob - catch admob error showAdmob");
-
setTimeout(_buildAdmob, 10000);
-
}
-
}
-
};
-
// ----------------------------------------------------------------------------
-
-
// ----------------------------------------------------------------------------
-
/**
-
* showAdvert : the unique function to call to start showing the ads
-
* objUI : the object to move or resize.
-
* alterType : The type of transformation for the object, can be : 'move' or 'resize' or '' (empty for a fixed banner)
-
* alterFrom : From where the object transformation should start : 'top' or 'bottom' of the objUI
-
*/
-
this.showAdvert = function(objUI,alterType,alterFrom) {
-
if (Titanium.Network.online) {
-
_objUI = objUI;
-
_alterFrom = alterFrom;
-
_alterType = alterType;
-
-
var postLayoutCallback = function(e,AdsAutoSwither) {
-
_objUI.removeEventListener('postlayout', postLayoutCallback);
-
_objUIinitTop = objUI.getTop(), _objUIinitBottom = objUI.rect.bottom, _objUIinitHeight = objUI.rect.height;
-
if (_objUIinitTop == 'undefined') {
-
// _objUIinitTop = _objUIinitBottom - _objUIinitHeight - 50;
-
}
-
Ti.API.info('_objUIinitTop :'+_objUIinitTop+' -- _objUIinitBottom :'+_objUIinitBottom+' -- _objUIinitHeight :'+_objUIinitHeight);
-
setTimeout(function(){
-
if (_useAdmob) {
-
Ti.Admob = require('ti.admob');
-
_buildAdmob();
-
}
-
if (_useIads) { setTimeout(_buildIads, _iadsStartDelay); }
-
},_globalDelayStart)
-
}
-
_objUI.addEventListener('postlayout', postLayoutCallback);
-
}
-
else { // No internet connection. Retry in 30sec
-
setTimeout(this.showAdvert, 30000);
-
}
-
};
-
}
-
module.exports = AdsAutoSwither;
adsAutoSwitcher.js is freely available on gitbub
Les meilleurs tweaks cydia utiles pour iPhone jailbreaké (MAJ 13/02/12)
Voici une petite liste (non) exhaustive de quelques petits tweaks pour votre iPhone/iPoad... Bien sur, je parle de tweaks et autres applis.. trouvés sur cydia, donc jailbreak... Je ne parle pas ici des tweaks évidents selon moi, comme sbsetings, lockinfo ou intelliscreenX.. Juste de p'tits trucs qui devraient être déjà intégrés par Apple!
Tous ces tweak sont compatibles iOS 5.0.1 pour le moment, et souvent l'étaient déjà sous iOS 4.x.
Action Menu
Description : Ajoute des actions sur la barre de copier/coller
Author : Ryan Petrich
http://rpetri.ch/cydia/actionmenu/
Activator
Description : Ou comment "vraiment" utiliser le multitouch du device!!
http://rpetri.ch/cydia/activator/
Repo : http://rpetri.ch/repo/
Delete Word
Description : Comme sur un ordi, shift+delete supprime le mot entier
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=deletewordData
FolderEnhancer (payant)
Description : Quitte à avoir des dossiers dans iOS, autant en avoir des vrais!
http://moreinfo.thebigboss.org/moreinfo/user_depictions/ashikase/jp.ashikase.folderenhancer/
iAppLocker
Description : Permet de protéger par code le lancement d'applis. Pas le meilleur, mais gratuit et simple.
http://modmyi.com/info/iapplocker.php
iPhoneDelivery
Description : iOS 5.. mais toujours pas les accusés de reception pour les sms... délirant!
http//code.google.com/p/iphone-delivery-report/
Repo : http://iphonedelivery.advinux.com/cydia/
ManualCorrect
Description : Change le comportement de l'autocorrection. Il faut taper sur la proposition pour qu'elle s'insère! Tellement plus pratique que de supporter des corrections trop souvent hasardeuses..
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=manualcorrectData
NCQuickDismiss
Description : Ajoute un bouton pour faire disparaitre les notifications (celles qui apparaissent en haut de l'écran) plus rapidement.
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=ncquickdismissDp
PreventSleep
Description : Toggle device from entering sleep mode.
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=preventsleepData
Pull To Dismiss
Description : Faire disparaitre le clavier grace à un glissement vers le bas (très utile dans les mails par ex)
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=pulltodismissDp
SnoozeOrStop
Description : Quand on est pas bien reveillé le matin.. peu s'avérer utile
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=snoozeorstopData
SwipeToMoveCursor (voir aussi SwipeShiftCaret)
Description : Comme son nom l'indique, un tweak qui permet de se déplacer dans un texte en cours d'écriture via des swipes à gauche ou à droite..
Attention, ce tweak ajoute aussi un tas de raccourcis clavier, comme qqv etc. Voir les commentaires de ce post.
http://hitoriblog.com/depiction/SwipeToMoveCursor.html
Homepage (en Japonais) : http://hitoriblog.com/?p=2327
Repo : http://hitoriblog.com/apt/
SwitcherCleaner
Description : Montre uniquement dans la barre des taches, les applis ouvertes, et ajoute par défaut le bouton pour les fermer!
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=switchercleanerDp
MAJ 13/02/12
SwipeNav
Description : Ce tweak vous permet de naviguer de facon "naturelle" entre les pages d'une application. Il permet de passer d'une page à l'autre simplement via un swipe sur l'écran.
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=swipenavData
SwipeShiftCaret
Description : Equivalent à "SwipeToMoveCursor" mais en plus simple, et surtout plus récent.
http://moreinfo.thebigboss.org/moreinfo/depiction.php?file=swipeshiftcaretDp
Les plateformes de téléchargement : Seedbox et direct download.
L'arrivée d'Hadopi et ses emules dans le monde, ont sans doute favorisé l'arrivée d'un nouveau type de service en ligne : Les plateformes de téléchargement.
Ces sociétés mettent à dispo, sous forme d'une application web le plus souvent, le moyen de récupérer tous types de contenus, via des torrents ou du direct download (megaupload, fileserve etc).
Vous donnez le lien ou le fichier torrent, et le service s'occupe du reste pour vous! Bien sur, ces sociétés ont des comptes premiums sur les site de direct download. Donc pas d'attente et gros débit..
Elles conservent ensuite sur le cloud les dits fichiers, afin que l'on puisse les récupérer plus tard, voir même les regarder en streaming pour les fichiers vidéos.
J'ai déjà eu l'occasion d'en tester 3 rapidement :
http://www.streamshark.net/
http://fetch.io
http://put.io/
J'ai une petite préférence pour fetch.io... mais c'est vraiment subjectif
Tous offrent la possibilité de tester leur service pendant quelques jours, avec en général un quotat de téléchargement et d'espace de stockage limité.
Ensuite, il faut passer à la caisse... et acheter de la bande passante et du stockage. Les prix sont assez similaires d'une plateforme à l'autre. Les tarifs commencent à moins de 5€ par mois! (Le prix d'une pseudo license globale... )
Et les débits pour ensuite récupérer ses fichiers plus que correct..
Cerise sur le gateau, en général, le service se charge également de recoller les morceaux d'un fichier (file.r01, r02... etc)
Ce genre de services, moyennant un petit pécule, peut se rendre très utile.. à garder sous le coude!
Si vous en connaissez d'autres, faites les connaitre en commentaire.
(re)connexion automatique à un VPN sous Ubuntu
En ces temps peu glorieux d'Hadopi et tous ses dérivés... un bon moyen de pouvoir surfer sans être espionné, est d'utiliser un VPN.
Pour ma part, j'ai été confronté à des problèmes de déconnexions intempestives, sans reconnexion automatique. Ce qui peut être parfois gênant...
Voilà donc un (bon) moyen de palier ce problème. Ce n'est surement pas la meilleure solution, et je ne suis pas un fou de linux.. mais au moins, elle me satisfait!
Cette solution se compose de 2 fichiers. Un "check_vpn" qui se charge de lancer le script principal à intervalles définis. Et "vpn_restart.py", script en python qui relance la connexion si celle ci déconnectée.
check_vpn
-
-
while [ 1 ]; do
-
echo -n $(date) "## "
-
sudo /home/bsoft/Bureau/vpn_restart.py #où le script est installé
-
sleep 60 #en secondes, temps de boucle du script
-
done
vpn_restart.py
-
#http://ubuntuforums.org/showthread.php?t=1316314
-
import sys
-
import os
-
import dbus
-
import gobject
-
from dbus.mainloop.glib import DBusGMainLoop
-
-
# The uuid of the VPN connection to activate
-
VPN_CONNECTION_UUID = "20d3d577-51b4-435c-b408-2a3f3c8a5463"
-
-
# The uuid of the connection that needs to be active to start the VPN connection
-
ACTIVE_CONNECTION_UUID = "recupere via get_active_conn(bus)"
-
-
# Mon conn ID
-
CONN_ID = "Auto eth0"
-
# Mon conn['type']
-
CONN_TYPE = "802-3-ethernet"
-
-
# some service, path and interface constants
-
NM_DBUS_SERVICE = "org.freedesktop.NetworkManager"
-
NM_DBUS_PATH = "/org/freedesktop/NetworkManager"
-
NM_DBUS_INTERFACE = "org.freedesktop.NetworkManager"
-
NM_DBUS_IFACE_CONNECTION_ACTIVE = "org.freedesktop.NetworkManager.Connection.Active"
-
NM_DBUS_SERVICE_SYSTEM_SETTINGS = "org.freedesktop.NetworkManagerSystemSettings"
-
NM_DBUS_SERVICE_USER_SETTINGS = "org.freedesktop.NetworkManagerUserSettings"
-
NM_DBUS_IFACE_SETTINGS = "org.freedesktop.NetworkManagerSettings"
-
NM_DBUS_PATH_SETTINGS = "/org/freedesktop/NetworkManagerSettings"
-
NM_DBUS_IFACE_SETTINGS_CONNECTION = "org.freedesktop.NetworkManagerSettings.Connection"
-
-
DBusGMainLoop(set_as_default=True)
-
-
nm_dbus_settings_services = (NM_DBUS_SERVICE_SYSTEM_SETTINGS, NM_DBUS_SERVICE_USER_SETTINGS)
-
-
def get_connections(bus, service):
-
proxy = bus.get_object(service, NM_DBUS_PATH_SETTINGS)
-
iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_IFACE_SETTINGS)
-
return iface.ListConnections()
-
-
def get_connection_by_uuid(bus, uuid):
-
for service in nm_dbus_settings_services:
-
for c in get_connections(bus, service):
-
proxy = bus.get_object(service, c)
-
iface = dbus.Interface(proxy, dbus_interface = NM_DBUS_IFACE_SETTINGS_CONNECTION)
-
settings = iface.GetSettings()
-
if settings['connection']['uuid'] == uuid:
-
return (c, service)
-
return None
-
-
def list_uuids(bus):
-
for service in nm_dbus_settings_services:
-
for c in get_connections(bus, service):
-
proxy = bus.get_object(service, c)
-
iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_IFACE_SETTINGS_CONNECTION)
-
settings = iface.GetSettings()
-
conn = settings['connection']
-
print "%s: %s - %s (%s)" % (service, conn['uuid'], conn['id'], conn['type'])
-
-
# recupere l'uuid de la connexion active via CONN_ID et CONN_TYPE
-
def get_active_conn(bus):
-
for service in nm_dbus_settings_services:
-
for c in get_connections(bus, service):
-
proxy = bus.get_object(service, c)
-
iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_IFACE_SETTINGS_CONNECTION)
-
settings = iface.GetSettings()
-
conn = settings['connection']
-
if conn['id'] == CONN_ID and conn['type'] == CONN_TYPE:
-
return conn['uuid']
-
-
def get_active_connection_path(bus, uuid):
-
proxy = bus.get_object(NM_DBUS_SERVICE, NM_DBUS_PATH)
-
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
-
active_connections = iface.Get(NM_DBUS_INTERFACE, 'ActiveConnections')
-
connection_and_service = get_connection_by_uuid(bus, uuid)
-
if connection_and_service == None:
-
return None
-
for a in active_connections:
-
proxy = bus.get_object(NM_DBUS_SERVICE, a)
-
iface = dbus.Interface(proxy, dbus_interface='org.freedesktop.DBus.Properties')
-
path = iface.Get(NM_DBUS_IFACE_CONNECTION_ACTIVE, 'Connection')
-
service = iface.Get(NM_DBUS_IFACE_CONNECTION_ACTIVE, 'ServiceName')
-
if service != connection_and_service[1]:
-
continue
-
proxy = bus.get_object(connection_and_service[1], path)
-
iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_IFACE_SETTINGS_CONNECTION)
-
settings = iface.GetSettings()
-
if settings['connection']['uuid'] == uuid:
-
return a
-
return None
-
-
def activate_connection(bus, vpn_connection, active_connection):
-
def reply_handler(opath):
-
print "<<SUCCESS>>"
-
sys.exit(0)
-
def error_handler(*args):
-
print "<<FAILURE>>"
-
sys.exit(1)
-
proxy = bus.get_object(NM_DBUS_SERVICE, NM_DBUS_PATH)
-
iface = dbus.Interface(proxy, dbus_interface=NM_DBUS_INTERFACE)
-
iface.ActivateConnection(NM_DBUS_SERVICE_USER_SETTINGS,
-
vpn_connection[0],
-
dbus.ObjectPath("/"),
-
active_connection,
-
reply_handler=reply_handler,
-
error_handler=error_handler)
-
-
bus = dbus.SystemBus()
-
-
print "connections:"
-
list_uuids(bus)
-
-
ACTIVE_CONNECTION_UUID = get_active_conn(bus)
-
-
if len(VPN_CONNECTION_UUID) < 1 or len(ACTIVE_CONNECTION_UUID) < 1:
-
print "you need to set the uuids"
-
sys.exit(0)
-
-
vpn_connection = get_connection_by_uuid(bus, VPN_CONNECTION_UUID)
-
if not vpn_connection:
-
print "Configured VPN connection is not known to NM, check VPN_CONNECTION_UUID."
-
sys.exit(1)
-
-
active_connection = get_connection_by_uuid(bus, ACTIVE_CONNECTION_UUID)
-
if not active_connection:
-
print "Configured active connection is not known to NM, check ACTIVE_CONNECTION_UUID."
-
sys.exit(1)
-
-
if get_active_connection_path(bus, VPN_CONNECTION_UUID) != None:
-
print "VPN connection already activated"
-
sys.exit(0)
-
-
active_connection_path = get_active_connection_path(bus, ACTIVE_CONNECTION_UUID)
-
if not active_connection_path:
-
print "The required connection isn't active at the moment"
-
sys.exit(0)
-
-
print "connecting to:\n '%s'\nwith active connection:\n '%s'" % (vpn_connection, active_connection)
-
-
activate_connection(bus, vpn_connection, active_connection_path)
-
-
loop = gobject.MainLoop()
-
loop.run()
Le script python peut très facilement être amélioré. On peut imaginer par exemple de fermer certaines applications lorsque la connexion VPN est morte..
Pour faire fonctionner le tout, il suffit de copier le script python où vous voulez.
Puis, de copier en admin (sudo) le script check_vpn dans /etc/init.d
Il faut le rendre exécutable (chmod u+x nom_du_fichier)
Puis il faut créer un lien symbolique du script dans /etc/rc2.d afin que celui ci démarre automatique avec le système.
ln -s /etc/init.d/check_vpn /etc/rc2.d/S88check_vpn
Et voilà!
Chez moi, sous Ubuntu 9.04, ca fonctionne très bien. Il faut bien entendu au préalable avoir une connexion VPN de configurée dans le network manager.