This file is indexed.

/usr/lib/python3/dist-packages/recurrence/base.py is in python3-django-recurrence 1.2.0-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
"""
Wrapper around the ``dateutil.rrule`` module.

Provides more consistent behavior with the rfc2445 specification,
notably differing from `dateutil.rrule`` in the handling of the
`dtstart` parameter and the additional handling of a `dtend`
parameter. Also, the `byweekday` parameter in `dateutil.rrule` is
`byday` in this package to reflect the specification. See the `Rule`
and `Recurrence` class documentation for details on the differences.
"""

import re
import datetime
import calendar

import pytz
import dateutil.rrule
from django.conf import settings
from django.utils import dateformat
from django.utils.translation import ugettext as _, pgettext as _p
from django.utils.six import string_types

from recurrence import exceptions


YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY = range(7)

(JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST,
 SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER) = range(1, 13)


localtz = pytz.timezone(settings.TIME_ZONE)


class Rule(object):
    """
    A recurrence rule.

    `Rule` is a representation of a rfc2445 `RECUR` type, used in
    the `RRULE` and `EXRULE` properties. More information about the
    `RECUR` type specification can be found in the rfc at
    http://www.ietf.org/rfc/rfc2445.txt.

    An `Rrule` wraps the `dateutil.rrule.rrule` class while adhering
    to the rfc2445 spec. Notably a `dtstart` parameter cannot be
    specified with a `Rule` unlike `dateutil.rrule.rrule` as only one
    `dtstart` can be used with a set of `RRULE` and `EXRULE` rfc2445
    properties, therefore the `Recurrence` class (which is based on
    `dateutil.rrule.rruleset`) accepts a `dtstart` parameter instead.
    `Recurrence` also accepts a `dtend` parameter.

    Documentation is largely sourced from the `dateutil.rrule.rrule`
    documentation at http://labix.org/python-dateutil

    :Variables:
        `freq` : int
            One of the enumerated constants `YEARLY`, `MONTHLY`,
            `WEEKLY`, `DAILY`, `HOURLY`, `MINUTELY`, or `SECONDLY`,
            specifying the base recurring frequency.

        `interval` : int
            The interval between each freq iteration. For example,
            when using YEARLY, an interval of 2 means once every two
            years, but with HOURLY, it means once every two hours. The
            default interval is 1.

        `wkst` : int
            The week start day. Must be one of the `MO`, `TU`, `WE`,
            `TH`, `FR`, `SA`, `SU` constants, or an integer,
            specifying the first day of the week. This will affect
            recurrences based on weekly periods. The default week
            start is got from `calendar.firstweekday()`, and may be
            modified by `calendar.setfirstweekday()`.

        `count` : int
            How many occurrences will be generated by this rule.

        `until` : datetime.datetime
            If given, this must be a `datetime.datetime` instance,
            that will specify the limit of the recurrence. If a
            recurrence instance happens to be the same as the
            `datetime.datetime` instance given in the `until` keyword,
            this will be the last occurrence.

        `bysetpos` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, positive or negative. Each given integer will
            specify an occurrence number, corresponding to the nth
            occurrence of the rule inside the frequency period. For
            example, a `bysetpos` of `-1` if combined with a `MONTHLY`
            frequency, and a `byday` of `(MO, TU, WE, TH, FR)`, will
            result in the last work day of every month.

        `bymonth` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, meaning the months to apply the recurrence to.

        `bymonthday` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, meaning the month days to apply the recurrence
            to.

        `byyearday` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, meaning the year days to apply the recurrence
            to.

        `byweekno` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, meaning the week numbers to apply the recurrence
            to. Week numbers have the meaning described in ISO8601,
            that is, the first week of the year is that containing at
            least four days of the new year.

        `byday` : int or sequence
            If given, it must be either an integer `(0 == MO)`, a
            sequence of integers, one of the weekday constants `(MO,
            TU, ...)`, or a sequence of these constants. When given,
            these variables will define the weekdays where the
            recurrence will be applied. It's also possible to use an
            argument n for the weekday instances, which will mean the
            nth occurrence of this weekday in the period. For example,
            with `MONTHLY`, or with `YEARLY` and `BYMONTH`, using
            `FR(1)` in byweekday will specify the first friday of the
            month where the recurrence happens.

        `byhour` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, meaning the hours to apply the recurrence to.

        `byminute` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, meaning the minutes to apply the recurrence to.

        `bysecond` : int or sequence
            If given, it must be either an integer, or a sequence of
            integers, meaning the seconds to apply the recurrence to.
    """
    byparams = (
        'bysetpos', 'bymonth', 'bymonthday', 'byyearday',
        'byweekno', 'byday', 'byhour', 'byminute', 'bysecond'
    )
    frequencies = (
        'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
        'HOURLY', 'MINUTELY', 'SECONDLY'
    )
    weekdays = (
        'MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'
    )
    firstweekday = calendar.firstweekday()

    def __init__(
        self, freq,
        interval=1, wkst=None, count=None, until=None, **kwargs
    ):
        """
        Create a new rule.

        See `Rule` class documentation for available `**kwargs` and
        parameter usage.
        """
        self.freq = freq
        self.interval = interval
        self.wkst = wkst
        self.count = count
        self.until = until

        for param in self.byparams:
            if param in kwargs:
                value = kwargs[param]
                if hasattr(value, '__iter__'):
                    value = list(value)
                    if not value:
                        value = []
                elif value is not None:
                    value = [value]
                else:
                    value = []
                setattr(self, param, value)
            else:
                setattr(self, param, [])

    def __hash__(self):
        byparam_values = []
        for param in self.byparams:
            byparam_values.append(param)
            byparam_values.extend(getattr(self, param, []) or [])
        return hash((
            self.freq, self.interval, self.wkst, self.count, self.until,
            tuple(byparam_values)))

    def __eq__(self, other):
        if not isinstance(other, Rule):
            raise TypeError('object to compare must be Rule object')
        return hash(self) == hash(other)

    def __ne__(self, other):
        return not self.__eq__(other)

    def to_text(self, short=False):
        return rule_to_text(self, short)

    def to_dateutil_rrule(self, dtstart=None, dtend=None, cache=False):
        """
        Create a `dateutil.rrule.rrule` instance from this `Rule`.

        :Parameters:
            `dtstart` : datetime.datetime
                The date/time the recurrence rule starts.

            `dtend` : datetime.datetime
                The rule should not yield occurrences past this
                date. Replaces `until` if `until` is greater than
                `dtend`. Note: `dtend` in this case does not count for
                an occurrence itself.

            `cache` : bool
                If given, it must be a boolean value specifying to
                enable or disable caching of results. If you will use
                the same `dateutil.rrule.rrule` instance multiple
                times, enabling caching will improve the performance
                considerably.

        :Returns:
            A `dateutil.rrule.rrule` instance.
        """
        kwargs = dict((p, getattr(self, p) or None) for p in self.byparams)
        # dateutil.rrule renames the parameter 'byweekday' by we're using
        # the parameter name originally specified by rfc2445.
        kwargs['byweekday'] = kwargs.pop('byday')

        until = self.until
        if until:
            until = normalize_offset_awareness(until, dtstart)
            if dtend:
                if until > dtend:
                    until = dtend
        elif dtend:
            until = dtend

        return dateutil.rrule.rrule(
            self.freq, dtstart, self.interval, self.wkst, self.count, until,
            cache=cache, **kwargs)


class Recurrence(object):
    """
    A combination of `Rule` and `datetime.datetime` instances.

    A `Recurrence` instance provides the combined behavior of the
    rfc2445 `DTSTART`, `DTEND`, `RRULE`, `EXRULE`, `RDATE`, and
    `EXDATE` propeties in generating recurring date/times.

    This is a wrapper around the `dateutil.rrule.rruleset` class while
    adhering to the rfc2445 spec. Notably a `dtstart` parameter can be
    given which cascades to all `dateutil.rrule.rrule` instances
    generated by included `Rule` instances. A `dtend` parameter has
    also been included to reflect the `DTEND` rfc2445 parameter.

    :Variables:
        `dtstart` : datetime.datetime
            Optionally specify the first occurrence. This defaults to
            `datetime.datetime.now()` when the occurrence set is
            generated.

        `dtend` : datetime.datetime
            Optionally specify the last occurrence.

        `rrules` : list
            A list of `Rule` instances to include in the recurrence
            set generation.

        `exrules` : list
            A list of `Rule` instances to include in the recurrence
            set exclusion list. Dates which are part of the given
            recurrence rules will not be generated, even if some
            inclusive `Rule` or `datetime.datetime` instances matches
            them.

        `rdates` : list
            A list of `datetime.datetime` instances to include in the
            occurrence set generation.

        `exdates` : list
            A list of `datetime.datetime` instances to exclude in the
            occurrence set generation. Dates included that way will
            not be generated, even if some inclusive `Rule` or
            `datetime.datetime` instances matches them.
    """
    def __init__(
        self, dtstart=None, dtend=None,
        rrules=[], exrules=[], rdates=[], exdates=[]
    ):
        """
        Create a new recurrence.

        Parameters map directly to instance attributes, see
        `Recurrence` class documentation for usage.
        """
        self._cache = {}

        self.dtstart = dtstart
        self.dtend = dtend

        self.rrules = list(rrules)
        self.exrules = list(exrules)
        self.rdates = list(rdates)
        self.exdates = list(exdates)

    def __iter__(self):
        return self.occurrences()

    def __unicode__(self):
        return serialize(self)

    def __hash__(self):
        return hash((
            self.dtstart, self.dtend,
            tuple(self.rrules), tuple(self.exrules),
            tuple(self.rdates), tuple(self.exdates)))

    def __bool__(self):
        if (self.dtstart or self.dtend or
            tuple(self.rrules) or tuple(self.exrules) or
            tuple(self.rdates) or tuple(self.exdates)):
            return True
        else:
            return False

    def __nonzero__(self):
        # Required for Python 2 compatibility
        return type(self).__bool__(self)

    def __eq__(self, other):
        if type(other) != type(self):
            return False
        if not isinstance(other, Recurrence):
            raise TypeError('object to compare must be Recurrence object')
        return hash(self) == hash(other)

    def __ne__(self, other):
        return not self.__eq__(other)

    def occurrences(
        self, dtstart=None, dtend=None, cache=False
    ):
        """
        Get a generator yielding `datetime.datetime` instances in this
        occurrence set.

        :Parameters:
            `dtstart` : datetime.datetime
                Optionally specify the first occurrence of the
                occurrence set. Defaults to `self.dtstart` if specified
                or `datetime.datetime.now()` if not when the
                occurrence set is generated.

            `dtend` : datetime.datetime
                Optionally specify the last occurrence of the
                occurrence set. Defaults to `self.dtend` if specified.

            `cache` : bool
                Whether to cache the occurrence set generator.

        :Returns:
            A sequence of `datetime.datetime` instances.
        """
        return self.to_dateutil_rruleset(dtstart, dtend, cache)

    def count(self, dtstart=None, dtend=None, cache=False):
        """
        Returns the number of occurrences in this occurrence set.

        :Parameters:
            `dtstart` : datetime.datetime
                Optionally specify the first occurrence of the
                occurrence set. Defaults to `self.dtstart` if specified
                or `datetime.datetime.now()` if not when the
                occurrence set is generated.

            `dtend` : datetime.datetime
                Optionally specify the last occurrence of the
                occurrence set. Defaults to `self.dtend` if specified.

            `cache` : bool
                Whether to cache the occurrence set generator.

        :Returns:
            The number of occurrences in this occurrence set.
        """
        return self.to_dateutil_rruleset(dtstart, dtend, cache).count()

    def before(
        self, dt, inc=False,
        dtstart=None, dtend=None, cache=False
    ):
        """
        Returns the last recurrence before the given
        `datetime.datetime` instance.

        :Parameters:
            `dt` : datetime.datetime
                The date to use as the threshold.

            `inc` : bool
                Defines what happens if `dt` is an occurrence. With
                `inc == True`, if `dt` itself is an occurrence, it
                will be returned.

            `dtstart` : datetime.datetime
                Optionally specify the first occurrence of the
                occurrence set. Defaults to `self.dtstart` if specified
                or `datetime.datetime.now()` if not when the
                occurrence set is generated.

            `dtend` : datetime.datetime
                Optionally specify the last occurrence of the
                occurrence set. Defaults to `self.dtend` if specified.

            `cache` : bool
                Whether to cache the occurrence set generator.

        :Returns:
            A `datetime.datetime` instance.
        """
        return self.to_dateutil_rruleset(
            dtstart, dtend, cache).before(dt, inc)

    def after(
        self, dt, inc=False,
        dtstart=None, dtend=None, cache=False
    ):
        """
        Returns the first recurrence after the given
        `datetime.datetime` instance.

        :Parameters:
            `dt` : datetime.datetime
                The date to use as the threshold.

            `inc` : bool
                Defines what happens if `dt` is an occurrence. With
                `inc == True`, if `dt` itself is an occurrence, it
                will be returned.

            `dtstart` : datetime.datetime
                Optionally specify the first occurrence of the
                occurrence set. Defaults to `self.dtstart` if specified
                or `datetime.datetime.now()` if not when the
                occurrence set is generated.

            `dtend` : datetime.datetime
                Optionally specify the last occurrence of the
                occurrence set. Defaults to `self.dtend` if specified.

            `cache` : bool
                Whether to cache the occurrence set generator.

        :Returns:
            A `datetime.datetime` instance.
        """
        return self.to_dateutil_rruleset(dtstart, cache).after(dt, inc)

    def between(
        self, after, before,
        inc=False, dtstart=None, dtend=None, cache=False
    ):
        """
        Returns the first recurrence after the given
        `datetime.datetime` instance.

        :Parameters:
            `after` : datetime.datetime
                Return dates after this date.

            `before` : datetime.datetime
                Return dates before this date.

            `inc` : bool
                Defines what happens if `after` and/or `before` are
                themselves occurrences. With `inc == True`, they will
                be included in the list, if they are found in the
                occurrence set.

            `dtstart` : datetime.datetime
                Optionally specify the first occurrence of the
                occurrence set. Defaults to `self.dtstart` if specified
                or `datetime.datetime.now()` if not when the
                occurrence set is generated.

            `dtend` : datetime.datetime
                Optionally specify the last occurrence of the
                occurrence set. Defaults to `self.dtend` if specified.

            `cache` : bool
                Whether to cache the occurrence set generator.

        :Returns:
            A sequence of `datetime.datetime` instances.
        """
        return self.to_dateutil_rruleset(
            dtstart, dtend, cache).between(after, before, inc)

    def to_dateutil_rruleset(self, dtstart=None, dtend=None, cache=False):
        """
        Create a `dateutil.rrule.rruleset` instance from this
        `Recurrence`.

        :Parameters:
            `dtstart` : datetime.datetime
                The date/time the recurrence rule starts. This value
                overrides the `dtstart` property specified by the
                `Recurrence` instance if its set.

            `dtstart` : datetime.datetime
                Optionally specify the first occurrence of the
                occurrence set. Defaults to `self.dtstart` if specified
                or `datetime.datetime.now()` if not when the
                occurrence set is generated.

            `cache` : bool
                If given, it must be a boolean value specifying to
                enable or disable caching of results. If you will use
                the same `dateutil.rrule.rrule` instance multiple
                times, enabling caching will improve the performance
                considerably.

        :Returns:
            A `dateutil.rrule.rruleset` instance.
        """
        # all datetimes used in dateutil.rrule objects will need to be
        # normalized to either offset-aware or offset-naive datetimes
        # to avoid exceptions. dateutil will use the tzinfo from the
        # given dtstart, which will cascade to other datetime objects.

        dtstart = dtstart or self.dtstart
        dtend = dtend or self.dtend
        if dtend:
            dtend = normalize_offset_awareness(dtend or self.dtend, dtstart)

        if cache:
            # we need to cache an instance for each unique dtstart
            # value because the occurrence values will differ.
            cached = self._cache.get(dtstart)
            if cached:
                return cached

        rruleset = dateutil.rrule.rruleset(cache=cache)

        for rrule in self.rrules:
            rruleset.rrule(rrule.to_dateutil_rrule(dtstart, dtend, cache))
        for exrule in self.exrules:
            rruleset.exrule(exrule.to_dateutil_rrule(dtstart, dtend, cache))

        if dtstart is not None:
            rruleset.rdate(dtstart)
        for rdate in self.rdates:
            rdate = normalize_offset_awareness(rdate, dtstart)
            if dtend is not None and rdate < dtend:
                rruleset.rdate(rdate)
            elif not dtend:
                rruleset.rdate(rdate)
        if dtend is not None:
            rruleset.rdate(dtend)

        for exdate in self.exdates:
            exdate = normalize_offset_awareness(exdate, dtstart)
            if dtend is not None and exdate < dtend:
                rruleset.exdate(exdate)
            elif not dtend:
                rruleset.exdate(exdate)

        if cache:
            self._cache[dtstart] = rruleset

        return rruleset


class Weekday(object):
    """
    Representation of a weekday.

    A `Weekday` is essentially an integer from 0 to 6, with an
    optional `index` which indicates its position in a month. For
    example, an `number` of 6 and an `index` of ``-1`` means the last
    sunday of the month. Weekday's with a specific index can be
    created by calling the existing `MO`, `TU`, `WE`, `TH`, `FR`,
    `SA`, `SU` constants::

        >>> SU(-1)
        -1SU

    `Weekday` objects have a smart equality test that can compare
    integers, other `Weekday` objects, and string constants as defined
    by rfc2445, such as '-1SU'.
    """
    def __init__(self, number, index=None):
        """
        Create a new weekday constant.

        :Parameters:
            `number` : int
                A number in `range(7)`.
            `index` : int
                An integer specifying the weekday's position in the
                month. A value of ``None`` or ``0`` means the index is
                ambiguous and represents all weekdays of that number.
        """
        int(number)

        if number > 6:
            raise ValueError('number must be in range(7)')
        self.number = number
        self.index = index

    def __call__(self, index):
        if index == self.index:
            return self
        else:
            return Weekday(self.number, index)

    def __hash__(self):
        if self.index:
            return hash((self.number, self.index))
        else:
            return hash(self.number)

    def __eq__(self, other):
        other = to_weekday(other)
        return (self.number, self.index) == (other.number, other.index)

    def __repr__(self):
        if self.index:
            return '%s%s' % (self.index, Rule.weekdays[self.number])
        else:
            return Rule.weekdays[self.number]

    weekday = property(lambda self: self.number)
    n = property(lambda self: self.index)


MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY = (
    MO, TU, WE, TH, FR, SA, SU) = WEEKDAYS = list(map(lambda n: Weekday(n), range(7)))


def to_weekday(token):
    """
    Attempt to convert an object to a `Weekday` constant.

    :Parameters:
        `token` : str, int, dateutil.rrule.weekday or `Weekday`
            Can be values such as `MO`, `SU(-2)`, `"-2SU"`, or an
            integer like `1` for Tuesday. dateutil.rrule.weekday`
            are returned unchanged.

    :Returns:
        A `dateutil.rrule.weekday` instance.
    """
    if isinstance(token, Weekday):
        return token
    if isinstance(token, dateutil.rrule.weekday):
        return Weekday(token.weekday, token.n)
    if isinstance(token, int):
        if token > 6:
            raise ValueError
        return WEEKDAYS[token]
    elif not token:
        raise ValueError
    elif isinstance(token, string_types) and token.isdigit():
        if int(token) > 6:
            raise ValueError
        return WEEKDAYS[int(token)]
    elif isinstance(token, string_types):
        const = token[-2:].upper()
        if const not in Rule.weekdays:
            raise ValueError
        nth = token[:-2]
        if not nth:
            return Weekday(list(Rule.weekdays).index(const))
        else:
            return Weekday(list(Rule.weekdays).index(const), int(nth))


def validate(rule_or_recurrence):
    if isinstance(rule_or_recurrence, Rule):
        obj = Recurrence(rrules=[rule_or_recurrence])
    else:
        obj = rule_or_recurrence
    try:
        if not isinstance(obj, Rule) and not isinstance(obj, Recurrence):
            raise exceptions.ValidationError('incompatible object')
    except TypeError:
        raise exceptions.ValidationError('incompatible object')

    def validate_dt(dt):
        if not isinstance(dt, datetime.datetime):
            raise exceptions.ValidationError('invalid datetime: %r' % dt)

    def validate_iterable(rule, param):
        try:
            [v for v in getattr(rule, param, []) if v]
        except TypeError:
            # TODO: I'm not sure it's possible to get here - all the
            # places we call validate_iterable convert single ints to
            # sequences, and other types raise TypeErrors earlier.
            raise exceptions.ValidationError(
                '%s parameter must be iterable' % param)

    def validate_iterable_ints(rule, param, min_value=None, max_value=None):
        for value in getattr(rule, param, []):
            try:
                value = int(value)
                if min_value is not None:
                    if value < min_value:
                        raise ValueError
                if max_value is not None:
                    if value > max_value:
                        raise ValueError
            except ValueError:
                raise exceptions.ValidationError(
                    'invalid %s parameter: %r' % (param, value))

    def validate_rule(rule):
        # validate freq
        try:
            Rule.frequencies[int(rule.freq)]
        except IndexError:
            raise exceptions.ValidationError(
                'invalid freq parameter: %r' % rule.freq)
        except ValueError:
            raise exceptions.ValidationError(
                'invalid freq parameter: %r' % rule.freq)

        # validate interval
        try:
            interval = int(rule.interval)
            if interval < 1:
                raise ValueError
        except ValueError:
            raise exceptions.ValidationError(
                'invalid interval parameter: %r' % rule.interval)

        # validate wkst
        if rule.wkst:
            try:
                to_weekday(rule.wkst)
            except ValueError:
                raise exceptions.ValidationError(
                    'invalide wkst parameter: %r' % rule.wkst)

        # validate until
        if rule.until:
            try:
                validate_dt(rule.until)
            except ValueError:
                # TODO: I'm not sure it's possible to get here
                # (validate_dt doesn't raise ValueError)
                raise exceptions.ValidationError(
                    'invalid until parameter: %r' % rule.until)

        # validate count
        if rule.count:
            try:
                int(rule.count)
            except ValueError:
                raise exceptions.ValidationError(
                    'invalid count parameter: %r' % rule.count)

        # TODO: Should we check that you haven't specified both
        # rule.count and rule.until? Note that we only serialize
        # rule.until if there's no rule.count.

        # validate byparams
        for param in Rule.byparams:
            validate_iterable(rule, param)
            if param == 'byday':
                for value in getattr(rule, 'byday', []):
                    try:
                        to_weekday(value)
                    except ValueError:
                        raise exceptions.ValidationError(
                            'invalid byday parameter: %r' % value)
            elif param == 'bymonth':
                validate_iterable_ints(rule, param, 1, 12)
            elif param == 'bymonthday':
                validate_iterable_ints(rule, param, 1, 31)
            elif param == 'byhour':
                validate_iterable_ints(rule, param, 0, 23)
            elif param == 'byminute':
                validate_iterable_ints(rule, param, 0, 59)
            elif param == 'bysecond':
                validate_iterable_ints(rule, param, 0, 59)
            else:
                validate_iterable_ints(rule, param)

    if obj.dtstart:
        validate_dt(obj.dtstart)
    if obj.dtend:
        validate_dt(obj.dtend)
    if obj.rrules:
        list(map(lambda rule: validate_rule(rule), obj.rrules))
    if obj.exrules:
        list(map(lambda rule: validate_rule(rule), obj.exrules))
    if obj.rdates:
        list(map(lambda dt: validate_dt(dt), obj.rdates))
    if obj.exdates:
        list(map(lambda dt: validate_dt(dt), obj.exdates))


def serialize(rule_or_recurrence):
    """
    Serialize a `Rule` or `Recurrence` instance.

    `Rule` instances are wrapped as an rrule in a `Recurrence`
    instance before serialization, and will serialize as the `RRULE`
    property.

    All `datetime.datetime` objects will be converted and serialized
    as UTC.

    :Returns:
        A rfc2445 formatted unicode string.
    """
    def serialize_dt(dt):
        if not dt.tzinfo:
            dt = localtz.localize(dt)
        dt = dt.astimezone(pytz.utc)

        return u'%s%s%sT%s%s%sZ' % (
            str(dt.year).rjust(4, '0'),
            str(dt.month).rjust(2, '0'),
            str(dt.day).rjust(2, '0'),
            str(dt.hour).rjust(2, '0'),
            str(dt.minute).rjust(2, '0'),
            str(dt.second).rjust(2, '0'),
        )

    def serialize_rule(rule):
        values = []
        values.append((u'FREQ', [Rule.frequencies[rule.freq]]))

        if rule.interval != 1:
            values.append((u'INTERVAL', [str(int(rule.interval))]))
        if rule.wkst:
            values.append((u'WKST', [Rule.weekdays[rule.wkst]]))

        if rule.count is not None:
            values.append((u'COUNT', [str(rule.count)]))
        elif rule.until is not None:
            values.append((u'UNTIL', [serialize_dt(rule.until)]))

        if rule.byday:
            days = []
            for d in rule.byday:
                d = to_weekday(d)
                # TODO - this if/else copies what Weekday's __repr__
                # does - perhaps we should refactor it into a __str__
                # method on Weekday?
                if d.index:
                    days.append(u'%s%s' % (d.index, Rule.weekdays[d.number]))
                else:
                    days.append(Rule.weekdays[d.number])
            values.append((u'BYDAY', days))

        remaining_params = list(Rule.byparams)
        remaining_params.remove('byday')
        for param in remaining_params:
            value_list = getattr(rule, param, None)
            if value_list:
                values.append((param.upper(), [str(n) for n in value_list]))

        return u';'.join(u'%s=%s' % (i[0], u','.join(i[1])) for i in values)

    if rule_or_recurrence is None:
        return None

    try:
        validate(rule_or_recurrence)
    except exceptions.ValidationError as error:
        raise exceptions.SerializationError(error.args[0])

    obj = rule_or_recurrence
    if isinstance(obj, Rule):
        obj = Recurrence(rrules=[obj])

    items = []

    if obj.dtstart:
        if obj.dtstart.tzinfo:
            dtstart = serialize_dt(obj.dtstart.astimezone(pytz.utc))
        else:
            dtstart = serialize_dt(
                localtz.localize(obj.dtstart).astimezone(pytz.utc))
        items.append((u'DTSTART', dtstart))
    if obj.dtend:
        if obj.dtend.tzinfo:
            dtend = serialize_dt(obj.dtend.astimezone(pytz.utc))
        else:
            dtend = serialize_dt(
                localtz.localize(obj.dtend).astimezone(pytz.utc))
        items.append((u'DTEND', dtend))

    for rrule in obj.rrules:
        items.append((u'RRULE', serialize_rule(rrule)))
    for exrule in obj.exrules:
        items.append((u'EXRULE', serialize_rule(exrule)))

    for rdate in obj.rdates:
        if rdate.tzinfo:
            rdate = rdate.astimezone(pytz.utc)
        else:
            rdate = localtz.localize(rdate).astimezone(pytz.utc)
        items.append((u'RDATE', serialize_dt(rdate)))
    for exdate in obj.exdates:
        if exdate.tzinfo:
            exdate = exdate.astimezone(pytz.utc)
        else:
            exdate = localtz.localize(exdate).astimezone(pytz.utc)
        items.append((u'EXDATE', serialize_dt(exdate)))

    return u'\n'.join(u'%s:%s' % i for i in items)


def deserialize(text):
    """
    Deserialize a rfc2445 formatted string.

    This is a basic parser that is a partial implementation of rfc2445
    which pertains to specifying recurring date/times. Limitations
    include:

      - Only collects `DTSTART`, `DTEND`, `RRULE`, `EXRULE`, `RDATE`,
        and `EXDATE` properties.

      - Does not capture parameter options (i.e. RDATE;VALUE=PERIOD).
        `dateutil.rrule` does not support anything other than
        `DATE-TIME` parameter types.

      - `VTIMEZONE` and `TZID` can't be specified, so dates without
        the 'Z' marker will be localized to
        `settings.TIME_ZONE`. `datetime.datetime` objects in
        `Recurrence`/`Rrule` objects will be serialized as UTC.

      - The `DTSTART`, `DTEND`, `RDATE` and `EXDATE` properties also
        only support the `DATE-TIME` type.

    :Returns:
        A `Recurrence` instance.
    """
    def deserialize_dt(text):
        try:
            year, month, day = int(text[:4]), int(text[4:6]), int(text[6:8])
        except ValueError:
            raise exceptions.DeserializationError('malformed date-time: %r' % text)
        if u'T' in text:
            # time is also specified
            try:
                hour, minute, second = (
                    int(text[9:11]), int(text[11:13]), int(text[13:15]))
            except ValueError:
                raise exceptions.DeserializationError('malformed date-time: %r' % text)
        else:
            # only date is specified, use midnight
            hour, minute, second = (0, 0, 0)
        if u'Z' in text:
            # time is in utc
            tzinfo = pytz.utc
        else:
            # right now there is no support for VTIMEZONE/TZID since
            # this is a partial implementation of rfc2445 so we'll
            # just use the time zone specified in the Django settings.
            tzinfo = localtz

        dt = datetime.datetime(
            year, month, day, hour, minute, second, tzinfo=tzinfo)
        dt = dt.astimezone(localtz)

        # set tz to settings.TIME_ZONE and return offset-naive datetime
        return datetime.datetime(
            dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second)

    dtstart, dtend, rrules, exrules, rdates, exdates = None, None, [], [], [], []

    tokens = re.compile(
        u'(DTSTART|DTEND|RRULE|EXRULE|RDATE|EXDATE)[^:]*:(.*)',
        re.MULTILINE).findall(text)

    if not tokens and text:
        raise exceptions.DeserializationError('malformed data')

    for label, param_text in tokens:
        if not param_text:
            raise exceptions.DeserializationError('empty property: %r' % label)
        if u'=' not in param_text:
            params = param_text
        else:
            params = {}
            param_tokens = filter(lambda p: p, param_text.split(u';'))
            for item in param_tokens:
                try:
                    param_name, param_value = map(
                        lambda i: i.strip(), item.split(u'=', 1))
                except ValueError:
                    raise exceptions.DeserializationError(
                        'missing parameter value: %r' % item)
                params[param_name] = list(map(
                    lambda i: i.strip(), param_value.split(u',')))

        if label in (u'RRULE', u'EXRULE'):
            kwargs = {}
            for key, value in params.items():
                if key == u'FREQ':
                    try:
                        kwargs[str(key.lower())] = list(
                            Rule.frequencies).index(value[0])
                    except ValueError:
                        raise exceptions.DeserializationError(
                            'bad frequency value: %r' % value[0])
                elif key == u'INTERVAL':
                    try:
                        kwargs[str(key.lower())] = int(value[0])
                    except ValueError:
                        raise exceptions.DeserializationError(
                            'bad interval value: %r' % value[0])
                elif key == u'WKST':
                    try:
                        kwargs[str(key.lower())] = to_weekday(value[0])
                    except ValueError:
                        raise exceptions.DeserializationError(
                            'bad weekday value: %r' % value[0])
                elif key == u'COUNT':
                    try:
                        kwargs[str(key.lower())] = int(value[0])
                    except ValueError:
                        raise exceptions.DeserializationError(
                            'bad count value: %r' % value[0])
                elif key == u'UNTIL':
                    kwargs[str(key.lower())] = deserialize_dt(value[0])
                elif key == u'BYDAY':
                    bydays = []
                    for v in value:
                        try:
                            bydays.append(to_weekday(v))
                        except ValueError:
                            raise exceptions.DeserializationError(
                                'bad weekday value: %r' % v)
                    kwargs[str(key.lower())] = bydays
                elif key.lower() in Rule.byparams:
                    numbers = []
                    for v in value:
                        try:
                            numbers.append(int(v))
                        except ValueError:
                            raise exceptions.DeserializationError(
                                'bad value: %r' % value)
                    kwargs[str(key.lower())] = numbers
                else:
                    raise exceptions.DeserializationError('bad parameter: %s' % key)
            if 'freq' not in kwargs:
                raise exceptions.DeserializationError(
                    'frequency parameter missing from rule')
            if label == u'RRULE':
                rrules.append(Rule(**kwargs))
            else:
                exrules.append(Rule(**kwargs))
        elif label == u'DTSTART':
            dtstart = deserialize_dt(params)
        elif label == u'DTEND':
            dtend = deserialize_dt(params)
        elif label == u'RDATE':
            rdates.append(deserialize_dt(params))
        elif label == u'EXDATE':
            exdates.append(deserialize_dt(params))

    return Recurrence(dtstart, dtend, rrules, exrules, rdates, exdates)


def rule_to_text(rule, short=False):
    """
    Render the given `Rule` as natural text.

    :Parameters:
        `short` : bool
            Use abbreviated labels, i.e. 'Fri' instead of 'Friday'.
    """
    frequencies = (
        _('annually'), _('monthly'), _('weekly'), _('daily'),
        _('hourly'), _('minutely'), _('secondly'),
    )
    timeintervals = (
        _('years'), _('months'), _('weeks'), _('days'),
        _('hours'), _('minutes'), _('seconds'),
    )

    if short:
        positional_display = {
            1: _('1st %(weekday)s'),
            2: _('2nd %(weekday)s'),
            3: _('3rd %(weekday)s'),
            -1: _('last %(weekday)s'),
            -2: _('2nd last %(weekday)s'),
            -3: _('3rd last %(weekday)s'),
        }
        weekdays_display = (
            _('Mon'), _('Tue'), _('Wed'),
            _('Thu'), _('Fri'), _('Sat'), _('Sun'),
        )
        months_display = (
            _('Jan'), _('Feb'), _('Mar'), _('Apr'),
            _p('month name', 'May'), _('Jun'), _('Jul'), _('Aug'),
            _('Sep'), _('Oct'), _('Nov'), _('Dec'),
        )

    else:
        positional_display = {
            1: _('first %(weekday)s'),
            2: _('second %(weekday)s'),
            3: _('third %(weekday)s'),
            4: _('fourth %(weekday)s'),
            -1: _('last %(weekday)s'),
            -2: _('second last %(weekday)s'),
            -3: _('third last %(weekday)s'),
        }
        weekdays_display = (
            _('Monday'), _('Tuesday'), _('Wednesday'),
            _('Thursday'), _('Friday'), _('Saturday'), _('Sunday'),
        )
        months_display = (
            _('January'), _('February'), _('March'), _('April'),
            _p('month name', 'May'), _('June'), _('July'), _('August'),
            _('September'), _('October'), _('November'), _('December'),
        )

    def get_positional_weekdays(rule):
        items = []
        if rule.bysetpos and rule.byday:
            for setpos in rule.bysetpos:
                for byday in rule.byday:
                    byday = to_weekday(byday)
                    items.append(
                        positional_display.get(setpos) % {
                            'weekday': weekdays_display[byday.number]})
        elif rule.byday:
            for byday in rule.byday:
                byday = to_weekday(byday)
                items.append(
                    positional_display.get(byday.index, '%(weekday)s') % {
                        'weekday': weekdays_display[byday.number]})
        return _(', ').join(items)

    parts = []

    if rule.interval > 1:
        parts.append(
            _('every %(number)s %(freq)s') % {
                'number': rule.interval,
                'freq': timeintervals[rule.freq]
            })
    else:
        parts.append(frequencies[rule.freq])

    if rule.freq == YEARLY:
        if rule.bymonth:
            # bymonths are 1-indexed (January is 1), months_display
            # are 0-indexed (January is 0).
            items = _(', ').join(
                [months_display[month] for month in
                 [month_index - 1 for month_index in rule.bymonth]])
            parts.append(_('each %(items)s') % {'items': items})
        if rule.byday or rule.bysetpos:
            parts.append(
                _('on the %(items)s') % {
                    'items': get_positional_weekdays(rule)})

    if rule.freq == MONTHLY:
        if rule.bymonthday:
            items = _(', ').join([
                dateformat.format(
                    datetime.datetime(1, 1, day), 'jS')
                for day in rule.bymonthday])
            parts.append(_('on the %(items)s') % {'items': items})
        elif rule.byday:
            if rule.byday or rule.bysetpos:
                parts.append(
                    _('on the %(items)s') % {
                        'items': get_positional_weekdays(rule)})

    if rule.freq == WEEKLY:
        if rule.byday:
            items = _(', ').join([
                weekdays_display[to_weekday(day).number]
                for day in rule.byday])
            parts.append(_('each %(items)s') % {'items': items})

    # daily freqencies has no additional formatting,
    # hour/minute/second formatting not supported

    if rule.count:
        if rule.count == 1:
            parts.append(_('occuring once'))
        else:
            parts.append(_('occuring %(number)s times') % {
                'number': rule.count})
    elif rule.until:
        parts.append(_('until %(date)s') % {
            'date': dateformat.format(rule.until, 'Y-m-d')})

    return _(', ').join(parts)


def normalize_offset_awareness(dt, from_dt=None):
    """
    Given two `datetime.datetime` objects, return the second object as
    timezone offset-aware or offset-naive depending on the existence
    of the first object's tzinfo.

    If the second object is to be made offset-aware, it is assumed to
    be in the local timezone (with the timezone derived from the
    TIME_ZONE setting). If it is to be made offset-naive, It is first
    converted to the local timezone before being made naive.

    :Parameters:
        `dt` : `datetime.datetime`
            The datetime object to make offset-aware/offset-naive.
        `from_dt` : `datetime.datetime`
            The datetime object to test the existence of a tzinfo. If
            the value is nonzero, it will be understood as
            offset-naive
    """
    if from_dt and from_dt.tzinfo and dt.tzinfo:
        return dt
    elif from_dt and from_dt.tzinfo and not dt.tzinfo:
        dt = localtz.localize(dt)
    elif dt.tzinfo:
        dt = dt.astimezone(localtz)
        dt = datetime.datetime(
            dt.year, dt.month, dt.day,
            dt.hour, dt.minute, dt.second)
    return dt


def from_dateutil_rrule(rrule):
    """
    Convert a `dateutil.rrule.rrule` instance to a `Rule` instance.

    :Returns:
        A `Rrule` instance.
    """
    kwargs = {}
    kwargs['freq'] = rrule._freq
    kwargs['interval'] = rrule._interval
    if rrule._wkst != 0:
        kwargs['wkst'] = rrule._wkst
    kwargs['bysetpos'] = rrule._bysetpos
    if rrule._count is not None:
        kwargs['count'] = rrule._count
    elif rrule._until is not None:
        kwargs['until'] = rrule._until

    days = []
    if (rrule._byweekday is not None and (
        WEEKLY != rrule._freq or len(rrule._byweekday) != 1 or
        rrule._dtstart.weekday() != rrule._byweekday[0])):
        # ignore byweekday if freq is WEEKLY and day correlates
        # with dtstart because it was automatically set by
        # dateutil
        days.extend(Weekday(n) for n in rrule._byweekday)

    if rrule._bynweekday is not None:
        days.extend(Weekday(*n) for n in rrule._bynweekday)

    if len(days) > 0:
        kwargs['byday'] = days

    if rrule._bymonthday is not None and len(rrule._bymonthday) > 0:
        if not (rrule._freq <= MONTHLY and len(rrule._bymonthday) == 1 and
                rrule._bymonthday[0] == rrule._dtstart.day):
            # ignore bymonthday if it's generated by dateutil
            kwargs['bymonthday'] = list(rrule._bymonthday)

    if rrule._bynmonthday is not None and len(rrule._bynmonthday) > 0:
        kwargs.setdefault('bymonthday', []).extend(rrule._bynmonthday)

    if rrule._bymonth is not None and len(rrule._bymonth) > 0:
        if (rrule._byweekday is not None or
            len(rrule._bynweekday or ()) > 0 or not (
            rrule._freq == YEARLY and len(rrule._bymonth) == 1 and
            rrule._bymonth[0] == rrule._dtstart.month)):
            # ignore bymonth if it's generated by dateutil
            kwargs['bymonth'] = list(rrule._bymonth)

    if rrule._byyearday is not None:
        kwargs['byyearday'] = list(rrule._byyearday)
    if rrule._byweekno is not None:
        kwargs['byweekno'] = list(rrule._byweekno)

    kwargs['byhour'] = list(rrule._byhour)
    kwargs['byminute'] = list(rrule._byminute)
    kwargs['bysecond'] = list(rrule._bysecond)
    if (rrule._dtstart.hour in rrule._byhour and
        rrule._dtstart.minute in rrule._byminute and
        rrule._dtstart.second in rrule._bysecond):
        # ignore byhour/byminute/bysecond automatically set by
        # dateutil from dtstart
        kwargs['byhour'].remove(rrule._dtstart.hour)
        kwargs['byminute'].remove(rrule._dtstart.minute)
        kwargs['bysecond'].remove(rrule._dtstart.second)

    return Rule(**kwargs)


def from_dateutil_rruleset(rruleset):
    """
    Convert a `dateutil.rrule.rruleset` instance to a `Recurrence`
    instance.

    :Returns:
        A `Recurrence` instance.
    """
    rrules = [from_dateutil_rrule(rrule) for rrule in rruleset._rrule]
    exrules = [from_dateutil_rrule(exrule) for exrule in rruleset._exrule]
    rdates = rruleset._rdate
    exdates = rruleset._exdate

    dts = [r._dtstart for r in rruleset._rrule] + rruleset._rdate
    if len(dts) > 0:
        dts.sort()
        dtstart = dts[0]
    else:
        dtstart = None

    return Recurrence(dtstart, rrules, exrules, rdates, exdates)