Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
.format(host=self.host, user=self.user),
**self._settings
)
j = r.json()
for link in j['links']:
if 'remotestorage' in link['rel']:
break
storage = urljoin(_ensure_slash(link['href']),
_ensure_slash(subpath))
props = link['properties']
oauth = props['http://tools.ietf.org/html/rfc6749#section-4.2']
self.endpoints = dict(storage=storage, oauth=oauth)
class RemoteStorage(Storage):
__doc__ = '''
:param account: remoteStorage account, ``"user@example.com"``.
''' + HTTP_STORAGE_PARAMETERS + '''
'''
storage_name = None
item_mimetype = None
fileext = None
def __init__(self, account, verify=True, verify_fingerprint=None,
auth_cert=None, access_token=None, **kwargs):
super(RemoteStorage, self).__init__(**kwargs)
self.session = Session(
account=account,
verify=verify,
verify_fingerprint=verify_fingerprint,
def test_collection_required(a_requires, b_requires, tmpdir, runner,
monkeypatch):
class TestStorage(Storage):
storage_name = 'test'
def __init__(self, require_collection, **kw):
if require_collection:
assert not kw.get('collection')
raise exceptions.CollectionRequired()
from vdirsyncer.cli.utils import storage_names
monkeypatch.setitem(storage_names._storages, 'test', TestStorage)
runner.write_with_general(dedent('''
[pair foobar]
a = "foo"
b = "bar"
collections = null
def __init__(self, token_file, client_id, client_secret, start_date=None,
end_date=None, item_types=(), **kwargs):
if not kwargs.get('collection'):
raise exceptions.CollectionRequired()
super().__init__(
token_file=token_file, client_id=client_id,
client_secret=client_secret, start_date=start_date,
end_date=end_date, item_types=item_types,
**kwargs
)
# This is ugly: We define/override the entire signature computed for the
# docs here because the current way we autogenerate those docs are too
# simple for our advanced argspec juggling in `vdirsyncer.storage.dav`.
__init__._traverse_superclass = base.Storage
class GoogleContactsStorage(dav.CardDAVStorage):
class session_class(GoogleSession):
# Google CardDAV is completely bonkers. Collection discovery doesn't
# work properly, well-known URI takes us directly to single collection
# from where we can't discover principal or homeset URIs (the PROPFINDs
# 404).
#
# So we configure the well-known URI here again, such that discovery
# tries collection enumeration on it directly. That appears to work.
url = 'https://www.googleapis.com/.well-known/carddav'
scope = ['https://www.googleapis.com/auth/carddav']
class discovery_class(dav.CardDAVStorage.discovery_class):
# Google CardDAV doesn't return any resourcetype prop.
url = self.url
if path:
url = urlparse.urljoin(self.url, path)
more = dict(self._settings)
more.update(kwargs)
return http.request(method, url, session=self._session, **more)
def get_default_headers(self):
return {
'User-Agent': self.useragent,
'Content-Type': 'application/xml; charset=UTF-8'
}
class DAVStorage(Storage):
# the file extension of items. Useful for testing against radicale.
fileext = None
# mimetype of items
item_mimetype = None
# XML to use when fetching multiple hrefs.
get_multi_template = None
# The LXML query for extracting results in get_multi
get_multi_data_query = None
# The Discover subclass to use
discovery_class = None
# The DAVSession class to use
session_class = DAVSession
_repr_attributes = ('username', 'url')
_property_table = {
import random
from .base import Storage, normalize_meta_value
from .. import exceptions
def _random_string():
return '{:.9f}'.format(random.random())
class MemoryStorage(Storage):
storage_name = 'memory'
'''
Saves data in RAM, only useful for testing.
'''
def __init__(self, fileext='', **kwargs):
if kwargs.get('collection') is not None:
raise exceptions.UserError('MemoryStorage does not support '
'collections.')
self.items = {} # href => (etag, item)
self.metadata = {}
self.fileext = fileext
super().__init__(**kwargs)
import urllib.parse as urlparse
from .. import exceptions
from ..http import prepare_auth
from ..http import prepare_client_cert
from ..http import prepare_verify
from ..http import request
from ..http import USERAGENT
from ..vobject import Item
from ..vobject import split_collection
from .base import Storage
class HttpStorage(Storage):
storage_name = 'http'
read_only = True
_repr_attributes = ('username', 'url')
_items = None
# Required for tests.
_ignore_uids = True
def __init__(self, url, username='', password='', verify=True, auth=None,
useragent=USERAGENT, verify_fingerprint=None, auth_cert=None,
**kwargs):
super().__init__(**kwargs)
self._settings = {
'auth': prepare_auth(auth, username, password),
'cert': prepare_client_cert(auth_cert),
from .. import exceptions, native
from .base import Storage
from ..vobject import Item
from functools import partial
import json
class RustStorage(Storage):
_native_storage = None
def _native(self, name):
return partial(
getattr(native.lib, 'vdirsyncer_storage_{}'.format(name)),
self._native_storage
)
@classmethod
def _static_native(cls, name):
return getattr(
native.lib,
'vdirsyncer_storage_{}_{}'.format(name, cls.storage_name)
)
def list(self):
def _get_key(self):
try:
with open(self._key_path, 'rb') as f:
return f.read()
except OSError:
pass
def _set_key(self, content):
checkdir(os.path.dirname(self._key_path), create=True)
with atomicwrites.atomic_write(self._key_path, mode='wb') as f:
f.write(content)
assert_permissions(self._key_path, 0o600)
class EtesyncStorage(Storage):
_collection_type = None
_item_type = None
_at_once = False
def __init__(self, email, secrets_dir, server_url=None, db_path=None,
**kwargs):
if kwargs.get('collection', None) is None:
raise ValueError('Collection argument required')
self._session = _Session(email, secrets_dir, server_url, db_path)
super().__init__(**kwargs)
self._journal = self._session.etesync.get(self.collection)
def _sync_journal(self):
self._session.etesync.sync_journal(self.collection)
storage_name = 'google_contacts'
def __init__(self, token_file, client_id, client_secret, **kwargs):
if not kwargs.get('collection'):
raise exceptions.CollectionRequired()
super().__init__(
token_file=token_file, client_id=client_id,
client_secret=client_secret,
**kwargs
)
# This is ugly: We define/override the entire signature computed for the
# docs here because the current way we autogenerate those docs are too
# simple for our advanced argspec juggling in `vdirsyncer.storage.dav`.
__init__._traverse_superclass = base.Storage
logger = logging.getLogger(__name__)
def _writing_op(f):
@functools.wraps(f)
def inner(self, *args, **kwargs):
if self._items is None or not self._at_once:
self.list()
rv = f(self, *args, **kwargs)
if not self._at_once:
self._write()
return rv
return inner
class SingleFileStorage(Storage):
storage_name = 'singlefile'
_repr_attributes = ('path',)
_write_mode = 'wb'
_append_mode = 'ab'
_read_mode = 'rb'
_items = None
_last_etag = None
def __init__(self, path, encoding='utf-8', **kwargs):
super().__init__(**kwargs)
path = os.path.abspath(expand_path(path))
checkfile(path, create=False)
self.path = path