imip-agent

Annotated imip_store.py

750:146c37781587
2015-09-18 Paul Boddie Replaced bisection usage since requests are not actually sorted.
paul@2 1
#!/usr/bin/env python
paul@2 2
paul@146 3
"""
paul@146 4
A simple filesystem-based store of calendar data.
paul@146 5
paul@146 6
Copyright (C) 2014, 2015 Paul Boddie <paul@boddie.org.uk>
paul@146 7
paul@146 8
This program is free software; you can redistribute it and/or modify it under
paul@146 9
the terms of the GNU General Public License as published by the Free Software
paul@146 10
Foundation; either version 3 of the License, or (at your option) any later
paul@146 11
version.
paul@146 12
paul@146 13
This program is distributed in the hope that it will be useful, but WITHOUT
paul@146 14
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
paul@146 15
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
paul@146 16
details.
paul@146 17
paul@146 18
You should have received a copy of the GNU General Public License along with
paul@146 19
this program.  If not, see <http://www.gnu.org/licenses/>.
paul@146 20
"""
paul@146 21
paul@30 22
from datetime import datetime
paul@68 23
from imiptools.config import STORE_DIR, PUBLISH_DIR
paul@301 24
from imiptools.data import make_calendar, parse_object, to_stream
paul@740 25
from imiptools.dates import format_datetime, get_datetime, to_timezone
paul@147 26
from imiptools.filesys import fix_permissions, FileBase
paul@458 27
from imiptools.period import FreeBusyPeriod
paul@147 28
from os.path import exists, isfile, join
paul@343 29
from os import listdir, remove, rmdir
paul@303 30
from time import sleep
paul@395 31
import codecs
paul@15 32
paul@50 33
class FileStore(FileBase):
paul@50 34
paul@50 35
    "A file store of tabular free/busy data and objects."
paul@50 36
paul@597 37
    def __init__(self, store_dir=None):
paul@597 38
        FileBase.__init__(self, store_dir or STORE_DIR)
paul@147 39
paul@303 40
    def acquire_lock(self, user, timeout=None):
paul@303 41
        FileBase.acquire_lock(self, timeout, user)
paul@303 42
paul@303 43
    def release_lock(self, user):
paul@303 44
        FileBase.release_lock(self, user)
paul@303 45
paul@648 46
    # Utility methods.
paul@648 47
paul@343 48
    def _set_defaults(self, t, empty_defaults):
paul@343 49
        for i, default in empty_defaults:
paul@343 50
            if i >= len(t):
paul@343 51
                t += [None] * (i - len(t) + 1)
paul@343 52
            if not t[i]:
paul@343 53
                t[i] = default
paul@343 54
        return t
paul@343 55
paul@343 56
    def _get_table(self, user, filename, empty_defaults=None):
paul@343 57
paul@343 58
        """
paul@343 59
        From the file for the given 'user' having the given 'filename', return
paul@343 60
        a list of tuples representing the file's contents.
paul@343 61
paul@343 62
        The 'empty_defaults' is a list of (index, value) tuples indicating the
paul@343 63
        default value where a column either does not exist or provides an empty
paul@343 64
        value.
paul@343 65
        """
paul@343 66
paul@702 67
        f = codecs.open(filename, "rb", encoding="utf-8")
paul@702 68
        try:
paul@702 69
            l = []
paul@702 70
            for line in f.readlines():
paul@702 71
                t = line.strip(" \r\n").split("\t")
paul@702 72
                if empty_defaults:
paul@702 73
                    t = self._set_defaults(t, empty_defaults)
paul@702 74
                l.append(tuple(t))
paul@702 75
            return l
paul@702 76
        finally:
paul@702 77
            f.close()
paul@702 78
paul@702 79
    def _get_table_atomic(self, user, filename, empty_defaults=None):
paul@702 80
paul@702 81
        """
paul@702 82
        From the file for the given 'user' having the given 'filename', return
paul@702 83
        a list of tuples representing the file's contents.
paul@702 84
paul@702 85
        The 'empty_defaults' is a list of (index, value) tuples indicating the
paul@702 86
        default value where a column either does not exist or provides an empty
paul@702 87
        value.
paul@702 88
        """
paul@702 89
paul@343 90
        self.acquire_lock(user)
paul@343 91
        try:
paul@702 92
            return self._get_table(user, filename, empty_defaults)
paul@343 93
        finally:
paul@343 94
            self.release_lock(user)
paul@343 95
paul@343 96
    def _set_table(self, user, filename, items, empty_defaults=None):
paul@343 97
paul@343 98
        """
paul@343 99
        For the given 'user', write to the file having the given 'filename' the
paul@343 100
        'items'.
paul@343 101
paul@343 102
        The 'empty_defaults' is a list of (index, value) tuples indicating the
paul@343 103
        default value where a column either does not exist or provides an empty
paul@343 104
        value.
paul@343 105
        """
paul@343 106
paul@702 107
        f = codecs.open(filename, "wb", encoding="utf-8")
paul@702 108
        try:
paul@702 109
            for item in items:
paul@747 110
                self._set_table_item(f, item, empty_defaults)
paul@702 111
        finally:
paul@702 112
            f.close()
paul@702 113
            fix_permissions(filename)
paul@702 114
paul@747 115
    def _set_table_item(self, f, item, empty_defaults=None):
paul@747 116
paul@747 117
        "Set in table 'f' the given 'item', using any 'empty_defaults'."
paul@747 118
paul@747 119
        if empty_defaults:
paul@747 120
            item = self._set_defaults(list(item), empty_defaults)
paul@747 121
        f.write("\t".join(item) + "\n")
paul@747 122
paul@702 123
    def _set_table_atomic(self, user, filename, items, empty_defaults=None):
paul@702 124
paul@702 125
        """
paul@702 126
        For the given 'user', write to the file having the given 'filename' the
paul@702 127
        'items'.
paul@702 128
paul@702 129
        The 'empty_defaults' is a list of (index, value) tuples indicating the
paul@702 130
        default value where a column either does not exist or provides an empty
paul@702 131
        value.
paul@702 132
        """
paul@702 133
paul@343 134
        self.acquire_lock(user)
paul@343 135
        try:
paul@702 136
            self._set_table(user, filename, items, empty_defaults)
paul@343 137
        finally:
paul@343 138
            self.release_lock(user)
paul@343 139
paul@648 140
    # Store object access.
paul@648 141
paul@329 142
    def _get_object(self, user, filename):
paul@329 143
paul@329 144
        """
paul@329 145
        Return the parsed object for the given 'user' having the given
paul@329 146
        'filename'.
paul@329 147
        """
paul@329 148
paul@329 149
        self.acquire_lock(user)
paul@329 150
        try:
paul@329 151
            f = open(filename, "rb")
paul@329 152
            try:
paul@329 153
                return parse_object(f, "utf-8")
paul@329 154
            finally:
paul@329 155
                f.close()
paul@329 156
        finally:
paul@329 157
            self.release_lock(user)
paul@329 158
paul@329 159
    def _set_object(self, user, filename, node):
paul@329 160
paul@329 161
        """
paul@329 162
        Set an object for the given 'user' having the given 'filename', using
paul@329 163
        'node' to define the object.
paul@329 164
        """
paul@329 165
paul@329 166
        self.acquire_lock(user)
paul@329 167
        try:
paul@329 168
            f = open(filename, "wb")
paul@329 169
            try:
paul@329 170
                to_stream(f, node)
paul@329 171
            finally:
paul@329 172
                f.close()
paul@329 173
                fix_permissions(filename)
paul@329 174
        finally:
paul@329 175
            self.release_lock(user)
paul@329 176
paul@329 177
        return True
paul@329 178
paul@329 179
    def _remove_object(self, filename):
paul@329 180
paul@329 181
        "Remove the object with the given 'filename'."
paul@329 182
paul@329 183
        try:
paul@329 184
            remove(filename)
paul@329 185
        except OSError:
paul@329 186
            return False
paul@329 187
paul@329 188
        return True
paul@329 189
paul@343 190
    def _remove_collection(self, filename):
paul@343 191
paul@343 192
        "Remove the collection with the given 'filename'."
paul@343 193
paul@343 194
        try:
paul@343 195
            rmdir(filename)
paul@343 196
        except OSError:
paul@343 197
            return False
paul@343 198
paul@343 199
        return True
paul@343 200
paul@670 201
    # User discovery.
paul@670 202
paul@670 203
    def get_users(self):
paul@670 204
paul@670 205
        "Return a list of users."
paul@670 206
paul@670 207
        return listdir(self.store_dir)
paul@670 208
paul@648 209
    # Event and event metadata access.
paul@648 210
paul@119 211
    def get_events(self, user):
paul@119 212
paul@119 213
        "Return a list of event identifiers."
paul@119 214
paul@138 215
        filename = self.get_object_in_store(user, "objects")
paul@119 216
        if not filename or not exists(filename):
paul@119 217
            return None
paul@119 218
paul@119 219
        return [name for name in listdir(filename) if isfile(join(filename, name))]
paul@119 220
paul@648 221
    def get_all_events(self, user):
paul@648 222
paul@648 223
        "Return a set of (uid, recurrenceid) tuples for all events."
paul@648 224
paul@648 225
        uids = self.get_events(user)
paul@674 226
        if not uids:
paul@674 227
            return set()
paul@648 228
paul@648 229
        all_events = set()
paul@648 230
        for uid in uids:
paul@648 231
            all_events.add((uid, None))
paul@648 232
            all_events.update([(uid, recurrenceid) for recurrenceid in self.get_recurrences(user, uid)])
paul@648 233
paul@648 234
        return all_events
paul@648 235
paul@694 236
    def get_event_filename(self, user, uid, recurrenceid=None, dirname=None):
paul@648 237
paul@694 238
        """
paul@694 239
        Get the filename providing the event for the given 'user' with the given
paul@694 240
        'uid'. If the optional 'recurrenceid' is specified, a specific instance
paul@694 241
        or occurrence of an event is returned.
paul@648 242
paul@694 243
        Where 'dirname' is specified, the given directory name is used as the
paul@694 244
        base of the location within which any filename will reside.
paul@694 245
        """
paul@648 246
paul@694 247
        if recurrenceid:
paul@694 248
            return self.get_recurrence_filename(user, uid, recurrenceid, dirname)
paul@694 249
        else:
paul@694 250
            return self.get_complete_event_filename(user, uid, dirname)
paul@648 251
paul@343 252
    def get_event(self, user, uid, recurrenceid=None):
paul@343 253
paul@343 254
        """
paul@343 255
        Get the event for the given 'user' with the given 'uid'. If
paul@343 256
        the optional 'recurrenceid' is specified, a specific instance or
paul@343 257
        occurrence of an event is returned.
paul@343 258
        """
paul@343 259
paul@694 260
        filename = self.get_event_filename(user, uid, recurrenceid)
paul@694 261
        if not filename or not exists(filename):
paul@694 262
            return None
paul@694 263
paul@694 264
        return filename and self._get_object(user, filename)
paul@694 265
paul@694 266
    def get_complete_event_filename(self, user, uid, dirname=None):
paul@694 267
paul@694 268
        """
paul@694 269
        Get the filename providing the event for the given 'user' with the given
paul@694 270
        'uid'. 
paul@694 271
paul@694 272
        Where 'dirname' is specified, the given directory name is used as the
paul@694 273
        base of the location within which any filename will reside.
paul@694 274
        """
paul@694 275
paul@694 276
        return self.get_object_in_store(user, dirname, "objects", uid)
paul@343 277
paul@343 278
    def get_complete_event(self, user, uid):
paul@50 279
paul@50 280
        "Get the event for the given 'user' with the given 'uid'."
paul@50 281
paul@694 282
        filename = self.get_complete_event_filename(user, uid)
paul@50 283
        if not filename or not exists(filename):
paul@50 284
            return None
paul@50 285
paul@694 286
        return filename and self._get_object(user, filename)
paul@50 287
paul@343 288
    def set_event(self, user, uid, recurrenceid, node):
paul@343 289
paul@343 290
        """
paul@343 291
        Set an event for 'user' having the given 'uid' and 'recurrenceid' (which
paul@343 292
        if the latter is specified, a specific instance or occurrence of an
paul@343 293
        event is referenced), using the given 'node' description.
paul@343 294
        """
paul@343 295
paul@343 296
        if recurrenceid:
paul@343 297
            return self.set_recurrence(user, uid, recurrenceid, node)
paul@343 298
        else:
paul@343 299
            return self.set_complete_event(user, uid, node)
paul@343 300
paul@343 301
    def set_complete_event(self, user, uid, node):
paul@50 302
paul@50 303
        "Set an event for 'user' having the given 'uid' and 'node'."
paul@50 304
paul@138 305
        filename = self.get_object_in_store(user, "objects", uid)
paul@50 306
        if not filename:
paul@50 307
            return False
paul@50 308
paul@329 309
        return self._set_object(user, filename, node)
paul@15 310
paul@365 311
    def remove_event(self, user, uid, recurrenceid=None):
paul@234 312
paul@343 313
        """
paul@343 314
        Remove an event for 'user' having the given 'uid'. If the optional
paul@343 315
        'recurrenceid' is specified, a specific instance or occurrence of an
paul@343 316
        event is removed.
paul@343 317
        """
paul@343 318
paul@343 319
        if recurrenceid:
paul@343 320
            return self.remove_recurrence(user, uid, recurrenceid)
paul@343 321
        else:
paul@343 322
            for recurrenceid in self.get_recurrences(user, uid) or []:
paul@343 323
                self.remove_recurrence(user, uid, recurrenceid)
paul@343 324
            return self.remove_complete_event(user, uid)
paul@343 325
paul@343 326
    def remove_complete_event(self, user, uid):
paul@343 327
paul@234 328
        "Remove an event for 'user' having the given 'uid'."
paul@234 329
paul@378 330
        self.remove_recurrences(user, uid)
paul@369 331
paul@234 332
        filename = self.get_object_in_store(user, "objects", uid)
paul@234 333
        if not filename:
paul@234 334
            return False
paul@234 335
paul@329 336
        return self._remove_object(filename)
paul@234 337
paul@334 338
    def get_recurrences(self, user, uid):
paul@334 339
paul@334 340
        """
paul@334 341
        Get additional event instances for an event of the given 'user' with the
paul@694 342
        indicated 'uid'. Both active and cancelled recurrences are returned.
paul@694 343
        """
paul@694 344
paul@694 345
        return self.get_active_recurrences(user, uid) + self.get_cancelled_recurrences(user, uid)
paul@694 346
paul@694 347
    def get_active_recurrences(self, user, uid):
paul@694 348
paul@694 349
        """
paul@694 350
        Get additional event instances for an event of the given 'user' with the
paul@694 351
        indicated 'uid'. Cancelled recurrences are not returned.
paul@334 352
        """
paul@334 353
paul@334 354
        filename = self.get_object_in_store(user, "recurrences", uid)
paul@334 355
        if not filename or not exists(filename):
paul@347 356
            return []
paul@334 357
paul@334 358
        return [name for name in listdir(filename) if isfile(join(filename, name))]
paul@334 359
paul@694 360
    def get_cancelled_recurrences(self, user, uid):
paul@694 361
paul@694 362
        """
paul@694 363
        Get additional event instances for an event of the given 'user' with the
paul@694 364
        indicated 'uid'. Only cancelled recurrences are returned.
paul@694 365
        """
paul@694 366
paul@694 367
        filename = self.get_object_in_store(user, "cancelled", "recurrences", uid)
paul@694 368
        if not filename or not exists(filename):
paul@694 369
            return []
paul@694 370
paul@694 371
        return [name for name in listdir(filename) if isfile(join(filename, name))]
paul@694 372
paul@694 373
    def get_recurrence_filename(self, user, uid, recurrenceid, dirname=None):
paul@694 374
paul@694 375
        """
paul@694 376
        For the event of the given 'user' with the given 'uid', return the
paul@694 377
        filename providing the recurrence with the given 'recurrenceid'.
paul@694 378
paul@694 379
        Where 'dirname' is specified, the given directory name is used as the
paul@694 380
        base of the location within which any filename will reside.
paul@694 381
        """
paul@694 382
paul@694 383
        return self.get_object_in_store(user, dirname, "recurrences", uid, recurrenceid)
paul@694 384
paul@334 385
    def get_recurrence(self, user, uid, recurrenceid):
paul@334 386
paul@334 387
        """
paul@334 388
        For the event of the given 'user' with the given 'uid', return the
paul@334 389
        specific recurrence indicated by the 'recurrenceid'.
paul@334 390
        """
paul@334 391
paul@694 392
        filename = self.get_recurrence_filename(user, uid, recurrenceid)
paul@334 393
        if not filename or not exists(filename):
paul@334 394
            return None
paul@334 395
paul@694 396
        return filename and self._get_object(user, filename)
paul@334 397
paul@334 398
    def set_recurrence(self, user, uid, recurrenceid, node):
paul@334 399
paul@334 400
        "Set an event for 'user' having the given 'uid' and 'node'."
paul@334 401
paul@334 402
        filename = self.get_object_in_store(user, "recurrences", uid, recurrenceid)
paul@334 403
        if not filename:
paul@334 404
            return False
paul@334 405
paul@334 406
        return self._set_object(user, filename, node)
paul@334 407
paul@334 408
    def remove_recurrence(self, user, uid, recurrenceid):
paul@334 409
paul@378 410
        """
paul@378 411
        Remove a special recurrence from an event stored by 'user' having the
paul@378 412
        given 'uid' and 'recurrenceid'.
paul@378 413
        """
paul@334 414
paul@378 415
        filename = self.get_object_in_store(user, "recurrences", uid, recurrenceid)
paul@334 416
        if not filename:
paul@334 417
            return False
paul@334 418
paul@334 419
        return self._remove_object(filename)
paul@334 420
paul@378 421
    def remove_recurrences(self, user, uid):
paul@378 422
paul@378 423
        """
paul@378 424
        Remove all recurrences for an event stored by 'user' having the given
paul@378 425
        'uid'.
paul@378 426
        """
paul@378 427
paul@378 428
        for recurrenceid in self.get_recurrences(user, uid):
paul@378 429
            self.remove_recurrence(user, uid, recurrenceid)
paul@378 430
paul@378 431
        recurrences = self.get_object_in_store(user, "recurrences", uid)
paul@378 432
        if recurrences:
paul@378 433
            return self._remove_collection(recurrences)
paul@378 434
paul@378 435
        return True
paul@378 436
paul@652 437
    # Free/busy period providers, upon extension of the free/busy records.
paul@652 438
paul@672 439
    def _get_freebusy_providers(self, user):
paul@672 440
paul@672 441
        """
paul@672 442
        Return the free/busy providers for the given 'user'.
paul@672 443
paul@672 444
        This function returns any stored datetime and a list of providers as a
paul@672 445
        2-tuple. Each provider is itself a (uid, recurrenceid) tuple.
paul@672 446
        """
paul@672 447
paul@672 448
        filename = self.get_object_in_store(user, "freebusy-providers")
paul@672 449
        if not filename or not exists(filename):
paul@672 450
            return None
paul@672 451
paul@672 452
        # Attempt to read providers, with a declaration of the datetime
paul@672 453
        # from which such providers are considered as still being active.
paul@672 454
paul@702 455
        t = self._get_table_atomic(user, filename, [(1, None)])
paul@672 456
        try:
paul@672 457
            dt_string = t[0][0]
paul@672 458
        except IndexError:
paul@672 459
            return None
paul@672 460
paul@672 461
        return dt_string, t[1:]
paul@672 462
paul@652 463
    def get_freebusy_providers(self, user, dt=None):
paul@652 464
paul@652 465
        """
paul@652 466
        Return a set of uncancelled events of the form (uid, recurrenceid)
paul@652 467
        providing free/busy details beyond the given datetime 'dt'.
paul@654 468
paul@654 469
        If 'dt' is not specified, all events previously found to provide
paul@654 470
        details will be returned. Otherwise, if 'dt' is earlier than the
paul@654 471
        datetime recorded for the known providers, None is returned, indicating
paul@654 472
        that the list of providers must be recomputed.
paul@672 473
paul@672 474
        This function returns a list of (uid, recurrenceid) tuples upon success.
paul@652 475
        """
paul@652 476
paul@672 477
        t = self._get_freebusy_providers(user)
paul@672 478
        if not t:
paul@672 479
            return None
paul@672 480
paul@672 481
        dt_string, t = t
paul@672 482
paul@672 483
        # If the requested datetime is earlier than the stated datetime, the
paul@672 484
        # providers will need to be recomputed.
paul@672 485
paul@672 486
        if dt:
paul@672 487
            providers_dt = get_datetime(dt_string)
paul@672 488
            if not providers_dt or providers_dt > dt:
paul@672 489
                return None
paul@672 490
paul@672 491
        # Otherwise, return the providers.
paul@672 492
paul@672 493
        return t[1:]
paul@672 494
paul@672 495
    def _set_freebusy_providers(self, user, dt_string, t):
paul@672 496
paul@672 497
        "Set the given provider timestamp 'dt_string' and table 't'."
paul@672 498
paul@652 499
        filename = self.get_object_in_store(user, "freebusy-providers")
paul@672 500
        if not filename:
paul@672 501
            return False
paul@652 502
paul@672 503
        t.insert(0, (dt_string,))
paul@702 504
        self._set_table_atomic(user, filename, t, [(1, "")])
paul@672 505
        return True
paul@652 506
paul@654 507
    def set_freebusy_providers(self, user, dt, providers):
paul@654 508
paul@654 509
        """
paul@654 510
        Define the uncancelled events providing free/busy details beyond the
paul@654 511
        given datetime 'dt'.
paul@654 512
        """
paul@654 513
paul@672 514
        t = []
paul@654 515
paul@654 516
        for obj in providers:
paul@672 517
            t.append((obj.get_uid(), obj.get_recurrenceid()))
paul@672 518
paul@672 519
        return self._set_freebusy_providers(user, format_datetime(dt), t)
paul@654 520
paul@672 521
    def append_freebusy_provider(self, user, provider):
paul@672 522
paul@672 523
        "For the given 'user', append the free/busy 'provider'."
paul@672 524
paul@672 525
        t = self._get_freebusy_providers(user)
paul@672 526
        if not t:
paul@654 527
            return False
paul@654 528
paul@672 529
        dt_string, t = t
paul@672 530
        t.append((provider.get_uid(), provider.get_recurrenceid()))
paul@672 531
paul@672 532
        return self._set_freebusy_providers(user, dt_string, t)
paul@672 533
paul@672 534
    def remove_freebusy_provider(self, user, provider):
paul@672 535
paul@672 536
        "For the given 'user', remove the free/busy 'provider'."
paul@672 537
paul@672 538
        t = self._get_freebusy_providers(user)
paul@672 539
        if not t:
paul@672 540
            return False
paul@672 541
paul@672 542
        dt_string, t = t
paul@672 543
        try:
paul@672 544
            t.remove((provider.get_uid(), provider.get_recurrenceid()))
paul@672 545
        except ValueError:
paul@672 546
            return False
paul@672 547
paul@672 548
        return self._set_freebusy_providers(user, dt_string, t)
paul@654 549
paul@648 550
    # Free/busy period access.
paul@648 551
paul@702 552
    def get_freebusy(self, user, name=None, get_table=None):
paul@15 553
paul@15 554
        "Get free/busy details for the given 'user'."
paul@15 555
paul@702 556
        filename = self.get_object_in_store(user, name or "freebusy")
paul@15 557
        if not filename or not exists(filename):
paul@167 558
            return []
paul@112 559
        else:
paul@702 560
            return map(lambda t: FreeBusyPeriod(*t),
paul@702 561
                (get_table or self._get_table_atomic)(user, filename, [(4, None)]))
paul@702 562
paul@702 563
    def get_freebusy_for_other(self, user, other, get_table=None):
paul@112 564
paul@112 565
        "For the given 'user', get free/busy details for the 'other' user."
paul@112 566
paul@112 567
        filename = self.get_object_in_store(user, "freebusy-other", other)
paul@167 568
        if not filename or not exists(filename):
paul@167 569
            return []
paul@112 570
        else:
paul@702 571
            return map(lambda t: FreeBusyPeriod(*t),
paul@702 572
                (get_table or self._get_table_atomic)(user, filename, [(4, None)]))
paul@702 573
paul@702 574
    def set_freebusy(self, user, freebusy, name=None, set_table=None):
paul@15 575
paul@15 576
        "For the given 'user', set 'freebusy' details."
paul@15 577
paul@702 578
        filename = self.get_object_in_store(user, name or "freebusy")
paul@15 579
        if not filename:
paul@15 580
            return False
paul@15 581
paul@702 582
        (set_table or self._set_table_atomic)(user, filename,
paul@702 583
            map(lambda fb: fb.as_tuple(strings_only=True), freebusy))
paul@15 584
        return True
paul@15 585
paul@702 586
    def set_freebusy_for_other(self, user, freebusy, other, set_table=None):
paul@110 587
paul@110 588
        "For the given 'user', set 'freebusy' details for the 'other' user."
paul@110 589
paul@110 590
        filename = self.get_object_in_store(user, "freebusy-other", other)
paul@110 591
        if not filename:
paul@110 592
            return False
paul@110 593
paul@702 594
        (set_table or self._set_table_atomic)(user, filename,
paul@702 595
            map(lambda fb: fb.as_tuple(strings_only=True), freebusy))
paul@112 596
        return True
paul@112 597
paul@710 598
    # Tentative free/busy periods related to countering.
paul@710 599
paul@710 600
    def get_freebusy_offers(self, user):
paul@710 601
paul@710 602
        "Get free/busy offers for the given 'user'."
paul@710 603
paul@710 604
        offers = []
paul@710 605
        expired = []
paul@741 606
        now = to_timezone(datetime.utcnow(), "UTC")
paul@710 607
paul@710 608
        # Expire old offers and save the collection if modified.
paul@710 609
paul@730 610
        self.acquire_lock(user)
paul@710 611
        try:
paul@730 612
            l = self.get_freebusy(user, "freebusy-offers")
paul@710 613
            for fb in l:
paul@710 614
                if fb.expires and get_datetime(fb.expires) <= now:
paul@710 615
                    expired.append(fb)
paul@710 616
                else:
paul@710 617
                    offers.append(fb)
paul@710 618
paul@710 619
            if expired:
paul@730 620
                self.set_freebusy_offers(user, offers)
paul@710 621
        finally:
paul@730 622
            self.release_lock(user)
paul@710 623
paul@710 624
        return offers
paul@710 625
paul@710 626
    def set_freebusy_offers(self, user, freebusy):
paul@710 627
paul@710 628
        "For the given 'user', set 'freebusy' offers."
paul@710 629
paul@710 630
        return self.set_freebusy(user, freebusy, "freebusy-offers")
paul@710 631
paul@747 632
    # Requests and counter-proposals.
paul@648 633
paul@142 634
    def _get_requests(self, user, queue):
paul@66 635
paul@142 636
        "Get requests for the given 'user' from the given 'queue'."
paul@66 637
paul@142 638
        filename = self.get_object_in_store(user, queue)
paul@81 639
        if not filename or not exists(filename):
paul@66 640
            return None
paul@66 641
paul@747 642
        return self._get_table_atomic(user, filename, [(1, None), (2, None)])
paul@66 643
paul@142 644
    def get_requests(self, user):
paul@142 645
paul@142 646
        "Get requests for the given 'user'."
paul@142 647
paul@142 648
        return self._get_requests(user, "requests")
paul@142 649
paul@142 650
    def _set_requests(self, user, requests, queue):
paul@66 651
paul@142 652
        """
paul@142 653
        For the given 'user', set the list of queued 'requests' in the given
paul@142 654
        'queue'.
paul@142 655
        """
paul@142 656
paul@142 657
        filename = self.get_object_in_store(user, queue)
paul@66 658
        if not filename:
paul@66 659
            return False
paul@66 660
paul@747 661
        self._set_table_atomic(user, filename, requests, [(1, ""), (2, "")])
paul@66 662
        return True
paul@66 663
paul@142 664
    def set_requests(self, user, requests):
paul@142 665
paul@142 666
        "For the given 'user', set the list of queued 'requests'."
paul@142 667
paul@142 668
        return self._set_requests(user, requests, "requests")
paul@142 669
paul@747 670
    def _set_request(self, user, request, queue):
paul@142 671
paul@343 672
        """
paul@747 673
        For the given 'user', set the given 'request' in the given 'queue'.
paul@343 674
        """
paul@142 675
paul@142 676
        filename = self.get_object_in_store(user, queue)
paul@55 677
        if not filename:
paul@55 678
            return False
paul@55 679
paul@303 680
        self.acquire_lock(user)
paul@55 681
        try:
paul@747 682
            f = codecs.open(filename, "ab", encoding="utf-8")
paul@303 683
            try:
paul@747 684
                self._set_table_item(f, request, [(1, ""), (2, "")])
paul@303 685
            finally:
paul@303 686
                f.close()
paul@303 687
                fix_permissions(filename)
paul@55 688
        finally:
paul@303 689
            self.release_lock(user)
paul@55 690
paul@55 691
        return True
paul@55 692
paul@747 693
    def set_request(self, user, uid, recurrenceid=None, type=None):
paul@142 694
paul@747 695
        """
paul@747 696
        For the given 'user', set the queued 'uid' and 'recurrenceid',
paul@747 697
        indicating a request, along with any given 'type'.
paul@747 698
        """
paul@142 699
paul@747 700
        return self._set_request(user, (uid, recurrenceid, type), "requests")
paul@747 701
paul@747 702
    def queue_request(self, user, uid, recurrenceid=None, type=None):
paul@142 703
paul@343 704
        """
paul@343 705
        Queue a request for 'user' having the given 'uid'. If the optional
paul@747 706
        'recurrenceid' is specified, the entry refers to a specific instance
paul@747 707
        or occurrence of an event. The 'type' parameter can be used to indicate
paul@747 708
        a specific type of request.
paul@747 709
        """
paul@747 710
paul@747 711
        requests = self.get_requests(user) or []
paul@747 712
paul@747 713
        if not self.have_request(requests, uid, recurrenceid):
paul@747 714
            return self.set_request(user, uid, recurrenceid, type)
paul@747 715
paul@747 716
        return False
paul@747 717
paul@747 718
    def dequeue_request(self, user, uid, recurrenceid=None, type=None):
paul@747 719
paul@747 720
        """
paul@747 721
        Dequeue all requests for 'user' having the given 'uid'. If the optional
paul@747 722
        'recurrenceid' is specified, all requests for that specific instance or
paul@747 723
        occurrence of an event are dequeued.
paul@343 724
        """
paul@66 725
paul@81 726
        requests = self.get_requests(user) or []
paul@750 727
        result = []
paul@747 728
paul@750 729
        for request in requests:
paul@750 730
            if request[:2] == (uid, recurrenceid):
paul@747 731
paul@750 732
                # Remove associated objects.
paul@747 733
paul@750 734
                type = request[2]
paul@750 735
                if type == "COUNTER":
paul@750 736
                    self.remove_counter(user, uid, recurrenceid)
paul@66 737
paul@750 738
            else:
paul@750 739
                result.append(request)
paul@747 740
paul@750 741
        self.set_requests(user, result)
paul@747 742
        return True
paul@747 743
paul@747 744
    def have_request(self, requests, uid, recurrenceid=None):
paul@750 745
        for request in requests:
paul@750 746
            if request[:2] == (uid, recurrenceid):
paul@750 747
                return True
paul@750 748
        return False
paul@747 749
paul@747 750
    def set_counter(self, user, node, uid, recurrenceid=None):
paul@105 751
paul@343 752
        """
paul@747 753
        For the given 'user', store the given 'node' for the given 'uid' and
paul@747 754
        'recurrenceid' as a counter-proposal.
paul@343 755
        """
paul@105 756
paul@747 757
        filename = self.get_event_filename(user, uid, recurrenceid, "counters")
paul@747 758
        if not filename:
paul@747 759
            return False
paul@747 760
paul@747 761
        return self._set_object(user, filename, node)
paul@747 762
paul@747 763
    def remove_counter(self, user, uid, recurrenceid=None):
paul@105 764
paul@747 765
        """
paul@747 766
        For the given 'user', remove any counter-proposal associated with the
paul@747 767
        given 'uid' and 'recurrenceid'.
paul@747 768
        """
paul@747 769
paul@747 770
        filename = self.get_event_filename(user, uid, recurrenceid, "counters")
paul@747 771
        if not filename:
paul@105 772
            return False
paul@747 773
paul@747 774
        return self._remove_object(filename)
paul@747 775
paul@747 776
    # Event cancellation.
paul@105 777
paul@343 778
    def cancel_event(self, user, uid, recurrenceid=None):
paul@142 779
paul@343 780
        """
paul@694 781
        Cancel an event for 'user' having the given 'uid'. If the optional
paul@694 782
        'recurrenceid' is specified, a specific instance or occurrence of an
paul@694 783
        event is cancelled.
paul@343 784
        """
paul@142 785
paul@694 786
        filename = self.get_event_filename(user, uid, recurrenceid)
paul@694 787
        cancelled_filename = self.get_event_filename(user, uid, recurrenceid, "cancellations")
paul@142 788
paul@694 789
        if filename and cancelled_filename and exists(filename):
paul@694 790
            return self.move_object(filename, cancelled_filename)
paul@142 791
paul@142 792
        return False
paul@142 793
paul@30 794
class FilePublisher(FileBase):
paul@30 795
paul@30 796
    "A publisher of objects."
paul@30 797
paul@597 798
    def __init__(self, store_dir=None):
paul@597 799
        FileBase.__init__(self, store_dir or PUBLISH_DIR)
paul@30 800
paul@30 801
    def set_freebusy(self, user, freebusy):
paul@30 802
paul@30 803
        "For the given 'user', set 'freebusy' details."
paul@30 804
paul@52 805
        filename = self.get_object_in_store(user, "freebusy")
paul@30 806
        if not filename:
paul@30 807
            return False
paul@30 808
paul@30 809
        record = []
paul@30 810
        rwrite = record.append
paul@30 811
paul@30 812
        rwrite(("ORGANIZER", {}, user))
paul@30 813
        rwrite(("UID", {}, user))
paul@30 814
        rwrite(("DTSTAMP", {}, datetime.utcnow().strftime("%Y%m%dT%H%M%SZ")))
paul@30 815
paul@458 816
        for fb in freebusy:
paul@458 817
            if not fb.transp or fb.transp == "OPAQUE":
paul@529 818
                rwrite(("FREEBUSY", {"FBTYPE" : "BUSY"}, "/".join(
paul@563 819
                    map(format_datetime, [fb.get_start_point(), fb.get_end_point()]))))
paul@30 820
paul@395 821
        f = open(filename, "wb")
paul@30 822
        try:
paul@30 823
            to_stream(f, make_calendar([("VFREEBUSY", {}, record)], "PUBLISH"))
paul@30 824
        finally:
paul@30 825
            f.close()
paul@103 826
            fix_permissions(filename)
paul@30 827
paul@30 828
        return True
paul@30 829
paul@2 830
# vim: tabstop=4 expandtab shiftwidth=4