1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
|
#
# $Id: Application.py,v 1.6 1999/12/16 10:00:32 rob Exp $
#
# Copyright 1999 Rob Tillotson <robt@debian.org>
# All Rights Reserved
#
# Permission to use, copy, modify, and distribute this software and
# its documentation for any purpose and without fee or royalty is
# hereby granted, provided that the above copyright notice appear in
# all copies and that both the copyright notice and this permission
# notice appear in supporting documentation or portions thereof,
# including modifications, that you you make.
#
# THE AUTHOR ROB TILLOTSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
# RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
# CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE!
#
"""Pyrite Application Subclass
"""
__version__ = '$Id: Application.py,v 1.6 1999/12/16 10:00:32 rob Exp $'
__copyright__ = 'Copyright 1999 Rob Tillotson <robt@debian.org>'
from types import ClassType
from whrandom import randint
import os, operator, string, time
import urlparse, urllib
if 'user' not in urlparse.uses_netloc: urlparse.uses_netloc.append('user')
from Pyrite import Plugin
from Pyrite.Store import Directory
import Sulfur
from Sulfur import Registry, Options, AppContext
from Sulfur import misc
import Sulfur.Application
import Pyrite
from Pyrite import protect_name, unprotect_name, Database, _
#
try:
import cPickle
pickle = cPickle
except:
import pickle
#
def _mkdir(d):
if os.path.exists(d):
if not os.path.isdir(d):
raise RuntimeError, _("%s exists, but is not a directory") % d
else:
os.mkdir(d)
#def find_user_directory(dd, u, id=None):
# if id:
# d = os.path.join(dd, protect_name('%s.%s' % (u, id)))
# try:
# os.stat(d)
# return d
# except os.error:
# pass
#
# d = os.path.join(dd, protect_name(u))
# try:
# os.stat(d)
# return d
# except os.error:
# return None
#def user_directory_name(data_directory, user, uid=None):
# if uid is not None:
# d = os.path.join(data_directory, protect_name('%s.%s' % (user, uid)))
# else:
# d = os.path.join(data_directory, protect_name(str(user)))
# return d
class Application(Sulfur.Application.Application):
"""A Pyrite application.
"""
type = 'PyriteApplication'
name = 'DefaultApplication'
app_prefix = 'Pyrite'
options = [
Options.Boolean('old-pdb', 0, _("use old prc/pdb access code"), None,
(), ['old-pdb']),
Options.Boolean('old-dlp', 0, _("use old DLP access code"), None,
(), ['old-dlp']),
Options.Boolean('debug', 0, _("enable debugging code"), None, (), ['debug']),
]
def __init__(self):
Sulfur.Application.Application.__init__(self)
self.port = None
self.default_user = None
self.default_uid = None
self.user = None
self.uid = None
self.sync_id = None
self.remote = None
self.state = {}
self.plugin_module_path.insert(0, 'Pyrite')
def prerun(self):
r = self.registry
# r = Registry.Registry()
# self.registry = r
# r.load('/etc/palm.conf', 'SYSTEM')
# r.load(os.path.expanduser('~/.palm.conf'), 'USER')
# Pyrite default plugin path
# pp = r.get('Pyrite::plugin-packages',[])
# if type(pp) != type([]): pp = [ pp ]
# for p in pp: self.plugin_module_path.append(p)
## FIXME do something intelligent with ports
# first, we try environment variables.
if os.environ.has_key('PYRITEPORT'):
self.port = os.environ['PYRITEPORT']
elif os.environ.has_key('PILOTPORT'):
self.port = os.environ['PILOTPORT']
else:
# select default port
if r.has_key('defaults::default-port'):
self.port = r.get('defaults::default-port')
if type(self.port) == type([]):
if self.port:
self.error(_("defaults::default-port option should not be a list."),'warning')
self.error(_("using %s as the default port.") % self.port[0], 'warning')
self.port = self.port[0]
else:
self.error(_("defaults::default-port is an empty list."),'warning')
self.port = None
else:
p = r.get('defaults::port','')
if type(p) == type([]):
if p:
self.port = p[0]
else:
self.error(_("defaults::port is an empty list."),'warning')
self.port = None
else:
# backward compatibility
if ',' in p: self.port = string.strip(string.split(p, ',')[0])
else: self.port = p
if not self.port:
self.error(_("no port specified in config file, using /dev/pilot"),'warning')
self.port = '/dev/pilot'
if os.environ.has_key('PYRITEPATH'):
self.data_directory = os.environ['PYRITEPATH']
else:
self.data_directory = os.path.expanduser(r.get('defaults::data-directory',''))
if not self.data_directory:
self.error(_("no data directory specified, using ~/Palm"),'warning')
self.data_directory = os.path.expanduser('~/Palm')
_mkdir(self.data_directory)
pydir = os.path.join(self.data_directory, 'Pyrite')
_mkdir(pydir)
# get saved state
try:
self.state = pickle.load(open(os.path.join(pydir,'state'),'r'))
except:
self.state = {}
# if the user and uid are specified in the conf file,
# we use them. otherwise, use the ones in the state.
if os.environ.has_key('PYRITEUSER'):
self.default_user = os.environ['PYRITEUSER']
else:
self.default_user = r.get('defaults::user',self.state.get('user',None))
if os.environ.has_key('PYRITEUID'):
self.default_uid = os.environ['PYRITEUID']
else:
self.default_uid = r.get('defaults::uid',self.state.get('uid',None))
# some defaults
if not self.default_uid:
self.error(_("no default user specified"),'warning')
if self.default_uid and self.default_user and not self.user_exists(self.default_uid):
self.user_add(self.default_uid, self.default_user)
# make a new PC ID if there isn't one already, or if the state file was
# written with a different version of Pyrite. (This makes sure to do
# a slow sync in case there have been any changes to Pyrite which might
# affect the fast sync logic or database contents etc.)
if not self.state.has_key('syncid') or \
not self.state.has_key('pyrite_version') or \
(self.state['pyrite_version'] != Pyrite.version):
from whrandom import randint
self.state['syncid'] = (randint(0, 65535) << 16 | randint(0, 65535))
self.sync_id = self.state.get('syncid',0)
# add products
if self.state.has_key('products'):
prd = {}
for pkg in self.state['products'].values():
# in the future, we will need to import all packages here,
# to check for callbacks.
if pkg and pkg not in self.plugin_module_path:
self.plugin_module_path.append(pkg)
self.change_user(self.default_uid)
def postrun(self):
self.state['user'] = self.user
self.state['uid'] = self.uid
self.state['syncid'] = self.sync_id
self.state['pyrite_version'] = Pyrite.version
if self.data_directory:
_mkdir(self.data_directory)
_mkdir(os.path.join(self.data_directory, 'Pyrite'))
try:
pickle.dump(self.state, open(os.path.join(self.data_directory,'Pyrite',
'state'),'w'))
except:
pass
if self.connected(): self.disconnect()
# def configure_user(self):
# if not self.user: return
# if self.registry.label() == 'PALMUSER':
# self.registry.pop()
#
# if not self.user_exists(self.user, self.uid):
# self.error(_("palmtop user '%s' does not have a directory; creating one"))
# self.user_add(self.user)
#
# try:
# d = find_user_directory(self.data_directory, self.user, self.uid)
# except:
# self.error(_("user '%s' might not exist") % self.user, 'error')
# return
#
# if d is None:
# self.error(_("user directory for '%s' not found") % self.user, 'error')
# return
#
# self.registry.load(os.path.join(d, 'palm.conf'), 'PALMUSER')
# self.configure(self.registry)
#
# for p in self.plugins.values():
# p.configure(self.registry)
# ----------------------------------------------------------------
# Connection Stuff
#
# Instantiating a DLP Store does not actually connect to the device;
# connection is deferred until the application actually does something
# with the Store, at which point the preconnect and postconnect
# functions are called at the appropriate time.
# ----------------------------------------------------------------
def preconnect(self, *a, **kw):
print _("Waiting for connection on %s (start the HotSync(R) application now)...") % self.port
def postconnect(self, store, *a, **kw):
self.log(_("Identifying user..."))
uinfo = store.user_info
self.log(_("User Name: %s") % uinfo['name'])
self.log(_("Last Sync: %s") % time.ctime(uinfo['lastSyncDate']))
self.log(_("Last Successful Sync: %s") % time.ctime(uinfo['successfulSyncDate']))
self.log(_("UID: %s VID: %s LastSyncPC: 0x%08x") % (uinfo['userID'],
uinfo['viewerID'],
uinfo['lastSyncPC']))
self.connect_user()
def connect(self, immediate=0):
"""Instantiate a remote store."""
if self.get_option('old-dlp'):
p = self.get_plugin('Store','OldDLP')
else:
p = self.get_plugin('Store','DLP')
self.remote = p(self.port, 0, self.preconnect, self.postconnect)
if immediate: self.remote.connect()
return self.remote
def disconnect(self, successful=1, log=_("Sync completed.")):
self.remote.disconnect(successful, log)
def connected(self):
return self.remote is not None and self.remote.connected()
# get something from the registry
# get an appmodule
# spool something for later install
def user_path(self, name=None, uid=None):
if uid is None: uid = self.uid
if not self.uid:
raise RuntimeError, _("uid is zero")
if name:
return os.path.join(self.data_directory, str(uid), name)
else:
return os.path.join(self.data_directory, str(uid))
def user_directory(self, dir='backup', make=1, uid=None):
"""Access a specific user data directory.
Returns an appropriate Directory Store object.
If the 'make' parameter is true (the default), and the
directory doesn't exist, it will be created.
"""
if uid is None: uid = self.uid
if not uid:
raise RuntimeError, _("uid is zero")
path = os.path.join(self.data_directory, str(uid), dir)
if make: _mkdir(path)
if self.get_option('old-pdb'):
p = self.get_plugin('Store','OldDirectory')
else:
p = self.get_plugin('Store','Directory')
s = p(path)
return s
# issue: expand to handle deeper levels?
# do we even need this function?
def user_directories(self):
"""List all available top-level user directories.
"""
p = os.path.join(self.data_directory, str(self.uid))
return filter(lambda x, path=p: os.path.isdir(os.path.join(path, x)),
os.listdir(p))
def open(self, name, mode='rs', dbclass=Database, **kw):
"""Open an arbitrary database.
This function can take either a filename or a URL as its argument.
The following URL types are acceptable:
http -- database is fetched and opened read-only
ftp -- database is fetched and opened read-only
file -- equivalent to filename if on 'localhost', otherwise
tries ftp
user -- open a database in a user directory:
user://username/directory/databasename
If attempting to open by filename fails, this function then tries
to open by *database name* in the current directory.
"""
scheme, loc, path, param, query, frag = urlparse.urlparse(name)
if scheme == 'user':
user = urllib.unquote(loc)
path, n = os.path.split(path)
if path and path[0] == '/': path = path[1:]
if not user: user = self.user
if not path: path = 'backup'
# avoid unnecessary making of directories
if 'w' in mode: make = 1
else: make = 0
try:
u = int(user)
except:
u = self.user_lookup(user)
if not u:
raise RuntimeError, _("user '%s' not found") % user
s = self.user_directory(path, make, u)
return apply(s.open, (n,mode,dbclass), kw)
elif scheme in ['http','ftp'] or \
(scheme == 'file' and loc and loc != 'localhost'):
p = self.get_plugin('Store','URL')
s = p(name)
l = s.list() # this actually fetches the file, it is now cached
return apply(s.open, (name,mode,dbclass), kw)
else:
if scheme == 'file': name = path
if self.get_option('old-pdb'):
p = self.get_plugin('Store','OldFile')
else:
p = self.get_plugin('Store','File')
s = p(name)
l = s.list()
# if this isn't a valid filename, try opening it as a
# database name instead.
if not l:
path, n = os.path.split(name)
if self.get_option('old-pdb'): p = self.get_plugin('Store','OldDirectory')
else: p = self.get_plugin('Store','Directory')
s = p(path)
name = n
return apply(s.open, (name,mode,dbclass), kw)
# --------------------------------------
# User Management
# --------------------------------------
# def user_exists(self, user, uid=None):
# return find_user_directory(self.data_directory, user, uid) is not None
#
# def user_add(self, user, uid=None):
# d = user_directory_name(self.data_directory, user, uid)
# _mkdir(d)
# _mkdir(os.path.join(d, 'backup'))
# _mkdir(os.path.join(d, 'install'))
#
# def user_delete(self, user, uid=None):
# import shutil
# d = find_user_directory(self.data_directory, user, uid)
# if d:
# shutil.rmtree(d, 1)
#
# def user_rename(self, user, newuser, uid=None, newuid=None):
# d = find_user_directory(self.data_directory, user, uid)
# n = user_directory_name(self.data_directory, newuser, newuid)
# os.rename(d, n)
#
# def user_list(self):
# l = []
# d = os.getcwd()
# os.chdir(self.data_directory)
# for dir in filter(os.path.isdir, os.listdir('.')):
# os.chdir(os.path.join(self.data_directory, dir))
# # simple rule to determine if this is probably a known user
# if os.path.isdir('backup') and os.path.isdir('install'):
# l.append(unprotect_name(dir))
# os.chdir(d)
# l.sort()
# return l
# user management, take two
# note: assumes self.remote is connected already
def connect_user(self):
user = self.remote.user_info['name']
uid = self.remote.user_info['userID']
rewrite = 0
if not user and not uid:
self.error(_("Pyrite does not support unidentified palmtops (yet)"))
return
if not uid:
uid = (randint(0, 65535) << 16 | randint(0, 65535))
self.error(_("Palm user ID is zero. Assigning a new one (%d).") % uid, 'warning')
rewrite = 1
if not self.user_exists(uid):
self.user_add(uid, user)
un = user
else:
un = self.user_name(uid)
if user != un:
self.error(_("Palm user name does not match. Restoring."), 'warning')
self.error(_("'%s' / '%s'") % (user, un))
user = un
self.remote.user_info['name'] = un
self.change_user(uid)
# change users. note that the user has to exist!
def change_user(self, uid):
if self.registry.label() == 'PALMUSER': self.registry.pop()
if not uid:
return
if not self.user_exists(uid):
raise RuntimeError, _("user #%d is unknown") % uid
self.uid = uid
self.user = self.user_name(uid)
self.registry.load(os.path.join(self.data_directory, str(uid), 'Pyrite', 'palm.conf'),
'PALMUSER')
for p in self.plugins.values():
p.configure(self.registry)
def user_add(self, uid, user):
ud = os.path.join(self.data_directory, str(uid))
# set up pyrite for a new user
_mkdir(ud)
_mkdir(os.path.join(ud, 'backup'))
_mkdir(os.path.join(ud, 'install'))
_mkdir(os.path.join(ud, 'Pyrite'))
if not user:
self.error(_("This palmtop has an empty user name."), 'warning')
user = '' # just in case it's None
open(os.path.join(ud, 'NAME'), 'w').write(user)
def user_name(self, uid):
try:
s = open(os.path.join(self.data_directory, str(uid), 'NAME')).readline()
if s[-1] == '\n': return s[:-1]
else: return s
except:
return ''
def user_exists(self, uid):
return os.path.isdir(os.path.join(self.data_directory, str(uid)))
def user_list(self):
l = []
_d = os.getcwd()
os.chdir(self.data_directory)
for dir in filter(os.path.isdir, os.listdir('.')):
try:
id = int(dir) # will throw exception if not a numeric dir name
l.append(id)
except:
continue
os.chdir(_d)
l.sort()
return l
def user_lookup(self, name):
for i in self.user_list():
if self.user_name(i) == name: return i
return 0
# ---------------------------
# Application Data Management
# ---------------------------
def app_path(self, path=None):
p = os.path.join(self.data_directory, self.app_prefix)
_mkdir(p)
if path: p = os.path.join(p, path)
return p
def app_user_path(self, path=None, uid=None):
if uid is None: uid = self.uid
if not uid:
raise RuntimeError, _("uid is zero")
p = os.path.join(self.data_directory, str(uid), self.app_prefix)
_mkdir(p)
if path: p = os.path.join(p, path)
return p
def user_open(self, name, mode='r', uid=None):
p = self.user_path(name, uid)
return open(p, mode)
def app_open(self, name, mode='r'):
p = self.app_path(name)
return open(p, mode)
def app_user_open(self, name, mode='r', uid=None):
p = self.app_user_path(name, uid)
return open(p, mode)
# # products: a product is a Pyrite add-on which provides plug-ins.
# # it is assumed to already be locatable on the Python path, and
# # these functions merely allow Pyrite to be aware that it exists
# # so that it can add all products to its search path
# # automatically.
# def product_install(self, package):
# if not self.state.has_key('products'):
# self.state['products'] = {}
# try:
# m = misc.import_module(package)
# except:
# m = None
# if not m:
# raise ImportError, _("Could not import package '%s'") % package
# if not hasattr(m, 'PYRITE_PRODUCT'):
# raise RuntimeError, _("Package '%s' does not appear to contain a Pyrite product.") % package
# name = m.PYRITE_PRODUCT['name']
# if package not in self.plugin_module_path:
# self.plugin_module_path.append(package)
# self.state['products'][name] = package
# return name
# def product_list(self):
# if not self.state.has_key('products'):
# self.state['products'] = {}
# l = []
# for name, pkg in self.state['products'].items():
# try:
# m = misc.import_module(pkg)
# except:
# continue
# if not hasattr(m, 'PYRITE_PRODUCT'):
# continue
# q = {'package': pkg,
# 'name': m.PYRITE_PRODUCT.get('name'),
# 'author': m.PYRITE_PRODUCT.get('author'),
# 'version': m.PYRITE_PRODUCT.get('version'),
# 'description': m.PYRITE_PRODUCT.get('description')
# }
# l.append(q)
# l.sort(lambda x,y: cmp(x.get('name'),y.get('name')))
# return l
# def product_remove(self, name):
# if not self.state.has_key('products'):
# self.state['products'] = {}
# if self.state['products'].has_key(name):
# p = self.state['products'][name]
# if p and p in self.plugin_module_path:
# self.plugin_module_path.remove(p)
# del self.state['products'][name]
# def product_installed(self, name):
# return self.state['products'].has_key(name)
# def product_info(self, name):
# for p in self.product_list():
# if p['name'] == name: return p
# return {}
# Backward compatibility (temporary overrides)
def get_plugin(self, collection, name, *a, **kw):
if collection == 'App':
self.error(_("using deprecated name for application modules; should be 'Connector', not 'App'"), 'warning')
collection = 'Connector'
return apply(Sulfur.Application.Application.get_plugin, (self, collection, name)+a, kw)
def __call__(self, *a, **kw):
ctx = PyriteCLIAppContext(self)
apply(ctx, a, kw)
class PyriteState(AppContext.PickleState):
def start(self, context):
AppContext.PickleState.start(self, context)
context.registry.load('/etc/palm.conf', 'SYSTEM')
context.registry.load(os.path.expanduser('~/.palm.conf'), 'USER')
class PyriteCLIAppContext(AppContext.CLIAppContext):
app_type = 'Pyrite'
def __init__(self, *a, **kw):
apply(AppContext.CLIAppContext.__init__, (self,)+a, kw)
self.state_manager = PyriteState()
|