File: protocol.py

package info (click to toggle)
taskcoach 1.4.1-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 32,496 kB
  • ctags: 17,810
  • sloc: python: 72,170; makefile: 254; ansic: 120; xml: 29; sh: 16
file content (1339 lines) | stat: -rw-r--r-- 44,914 bytes parent folder | download
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
1333
1334
1335
1336
1337
1338
1339
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2014 Task Coach developers <developers@taskcoach.org>

Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Task Coach is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

# pylint: disable=W0201,E1101
 
from taskcoachlib.domain.date import Date, parseDate, DateTime, parseDateTime, Recurrence

from taskcoachlib.domain.category import Category
from taskcoachlib.domain.task import Task
from taskcoachlib.domain.effort import Effort

from taskcoachlib.i18n import _

from twisted.internet.protocol import Protocol, ServerFactory
from twisted.internet.error import CannotListenError

import wx, struct, \
    random, time, hashlib, cStringIO, socket, os

# Default port is 8001.
#
# Integers are sent as 32 bits signed, network byte order.
# Strings are sent as their length (as integer), then data (UTF-8
# encoded). The length is computed after encoding.
# Dates are sent as strings, formatted YYYY-MM-DD.
#
# The exact workflow for both desktop and device is documented as Dia
# diagrams, in the "Design" subdirectory of the iPhone sources.

###############################################################################
#{ Support classes: object serialisation & packing


class BaseItem(object):
    """This is the base class of the network packet system. Each
    subclass maps to a particular type of data.

    @ivar state: convenience instance variable which starts as 0, used
        in subclasses to implement simple FSA."""

    def __init__(self):
        super(BaseItem, self).__init__()

        self.start()

    def start(self):
        """This method should reinitialize the instance."""
        self.state = 0
        self.value = None

    def expect(self):
        """This should return the number of bytes that are needed
        next. When this much bytes are finally available, they'll be
        passed to L{feed}. Return None if you're finished."""

        raise NotImplementedError

    def feed(self, data):
        """The bytes requested from L{expect} are available ('data'
        parameter)."""

        raise NotImplementedError

    def pack(self, value):
        """Unserialization. This should return a byte buffer
        representing 'value'."""

        raise NotImplementedError


class IntegerItem(BaseItem):
    """Integers. Packed as 32-bits, signed, big endian. Underlying
    type: int."""

    def expect(self):
        if self.state == 0:
            return 4
        else:
            return None

    def feed(self, data):
        self.value, = struct.unpack('!i', data)
        self.state = 1

    def pack(self, value):
        return struct.pack('!i', value)


class DataItem(BaseItem):
    """A bunch of bytes, the count being well known"""

    def __init__(self, count):
        super(DataItem, self).__init__()

        self.__count = count

    def expect(self):
        return self.__count if self.state == 0 else None

    def feed(self, data):
        if self.state == 0:
            self.value = data
            self.state = 1

    def pack(self, value):
        return value


class StringItem(BaseItem):
    """Strings. Encoded in UTF-8. Packed as their length (encoded),
    then the data. Underlying type: unicode."""

    def expect(self):
        if self.state == 0:
            return 4
        elif self.state == 1:
            return self.length
        else:
            return None

    def feed(self, data):
        if self.state == 0:
            self.length, = struct.unpack('!i', data)
            if self.length:
                self.state = 1
            else:
                self.value = u''
                self.state = 2
        elif self.state == 1:
            self.value = data.decode('UTF-8')
            self.state = 2

    def pack(self, value):
        v = value.encode('UTF-8')
        return struct.pack('!i', len(v)) + v


class FixedSizeStringItem(StringItem):
    """Same as L{StringItem}, but cannot be empty. Underlying type:
    unicode or NoneType."""

    def feed(self, data):
        super(FixedSizeStringItem, self).feed(data)

        if self.state == 2:
            if not self.value:
                self.value = None

    def pack(self, value):
        if value is None:
            return struct.pack('!i', 0)
        return super(FixedSizeStringItem, self).pack(value)


class DateItem(FixedSizeStringItem):
    """Date, in YYYY-MM-DD format. Underlying type:
    taskcoachlib.domain.date.Date."""

    def feed(self, data):
        super(DateItem, self).feed(data)

        if self.state == 2:
            self.value = Date() if self.value is None else parseDate(self.value)

    def pack(self, value):
        if isinstance(value, DateTime):
            value = Date(value.year, value.month, value.day)

        value = None if value == Date() else value.isoformat()
        return super(DateItem, self).pack(value)


class DateTimeItem(FixedSizeStringItem):
    """Date and time, YYYY-MM-DD HH:MM:SS"""

    def feed(self, data):
        super(DateTimeItem, self).feed(data)

        if self.state == 2:
            if self.value is not None:
                self.value = parseDateTime(self.value)

    def pack(self, value):
        if value is not None:
            value = value.replace(microsecond=0, tzinfo=None).isoformat(sep=' ')
        return super(DateTimeItem, self).pack(value)


class InfiniteDateTimeItem(FixedSizeStringItem):
    """Same as L{DateTimeItem}, but 'no date' is a DateTime() value
    instead of None."""

    def feed(self, data):
        super(InfiniteDateTimeItem, self).feed(data)

        if self.state == 2:
            if self.value is None:
                self.value = DateTime()
            else:
                self.value = parseDateTime(self.value)

    def pack(self, value):
        if value == DateTime():
            value = None
        if value is not None:
            value = value.replace(microsecond=0, tzinfo=None).isoformat(sep=' ')
        return super(InfiniteDateTimeItem, self).pack(value)


class CompositeItem(BaseItem):
    """A succession of several types. Underlying type: tuple. An
    exception is made if there is only 1 child, the type is then the
    same as it."""

    def __init__(self, items, *args, **kwargs):
        self._items = items

        super(CompositeItem, self).__init__(*args, **kwargs)

    def append(self, item):
        self._items.append(item)

    def start(self):
        super(CompositeItem, self).start()

        self.value = []

        for item in self._items:
            item.start()

    def expect(self):
        if self.state < len(self._items):
            expect = self._items[self.state].expect()

            if expect is None:
                self.value.append(self._items[self.state].value)
                self.state += 1
                return self.expect()

            return expect
        else:
            self.value = self.value[0] if len(self._items) == 1 else tuple(self.value)
            return None

    def feed(self, data):
        self._items[self.state].feed(data)

    def pack(self, *values):
        if len(self._items) == 1:
            return self._items[0].pack(values[0])
        else:
            return ''.join([self._items[idx].pack(v) \
                            for idx, v in enumerate(values)])

    def __str__(self):
        return 'CompositeItem([%s])' % ', '.join(map(str, self._items)) # pylint: disable=W0141


class ListItem(BaseItem):
    """A list of items. Underlying type: list."""

    def __init__(self, item, *args, **kwargs):
        self._item = item

        super(ListItem, self).__init__(*args, **kwargs)

    def start(self):
        super(ListItem, self).start()

        self.value = []

        self._item.start()

    def append(self, item):
        self._item.append(item)

    def expect(self):
        if self.state == 0:
            return 4
        elif self.state == 1:
            expect = self._item.expect()

            if expect is None:
                self.value.append(self._item.value)
                self.__count -= 1
                if self.__count == 0:
                    return None
                self._item.start()
                return self.expect()
            else:
                return expect
        elif self.state == 2:
            return None

    def feed(self, data):
        if self.state == 0:
            self.__count, = struct.unpack('!i', data)
            if self.__count:
                self._item.start()
                self.state = 1
            else:
                self.state = 2
        elif self.state == 1:
            self._item.feed(data)

    def pack(self, value):
        return struct.pack('!i', len(value)) + \
               ''.join([self._item.pack(v) for v in value])

    def __str__(self):
        return 'ListItem(%s)' % str(self._item)


class ItemParser(object):
    """Utility to avoid instantiating the Item classes by
    hand. parse('is[zi]') will hold a CompositeItem([IntegerItem(),
    StringItem(), ListItem(CompositeItem([FixedSizeStringItem(),
    IntegerITem()]))])."""

    # Special case for DataItem.

    formatMap = { 'i': IntegerItem,
                  's': StringItem,
                  'z': FixedSizeStringItem,
                  'd': DateItem,
                  't': DateTimeItem,
                  'f': InfiniteDateTimeItem }

    def __init__(self):
        super(ItemParser, self).__init__()

    @classmethod
    def registerItemType(klass, character, itemClass):
        """Register a new type of item. 'character' must be a
        single-character string, not already associated with an
        item. 'itemClass' should be a L{BaseItem} subclass. Its
        constructor must not take any parameter."""

        if len(character) != 1:
            raise ValueError('character must be a single character, not "%s".' % character)

        if character in klass.formatMap:
            raise ValueError('"%s" is already registered.' % character)

        klass.formatMap[character] = itemClass

    def parse(self, format): # pylint: disable=W0622
        if format.startswith('['):
            return ListItem(self.parse(format[1:-1]))

        current = CompositeItem([])
        stack = []
        count = None

        for character in format:
            if character == '[':
                item = ListItem(CompositeItem([]))
                stack.append(current)
                current.append(item)
                current = item
            elif character == ']':
                current = stack.pop()
            elif character == 'b':
                if count is None:
                    raise ValueError('Wrong format string: %s' % format)
                current.append(DataItem(count))
                count = None
            elif character.isdigit():
                if count is None:
                    count = int(character)
                else:
                    count *= 10
                    count += int(character)
            else:
                current.append(self.formatMap[character]())

        assert len(stack) == 0

        return current


class State(object):
    def __init__(self, disp):
        super(State, self).__init__()

        self.__disp = disp

    def init(self, format, count): # pylint: disable=W0622
        self.__format = format
        self.__count = count

        self.__data = cStringIO.StringIO()

        if format is None:
            self.__item = None
        else:
            self.__item = ItemParser().parse(format)

            if self.__count == 0:
                self.finished()
            else:
                self.__disp.set_terminator(self.__item.expect())

    def setState(self, klass, *args, **kwargs):
        self.__class__ = klass
        self.init(*args, **kwargs)

    def data(self):
        return self.__data.getvalue()

    def disp(self):
        return self.__disp

    def collect_incoming_data(self, data):
        if self.__format is not None:
            self.__data.write(data)

    def found_terminator(self):
        if self.__format is not None:
            self.__item.feed(self.__data.getvalue())
            self.__data = cStringIO.StringIO()

            length = self.__item.expect()
            if length is None:
                value = self.__item.value

                self.__count -= 1
                if self.__count:
                    self.__item.start()
                    self.__disp.set_terminator(self.__item.expect())

                self.handleNewObject(value)

                if not self.__count:
                    self.finished()
            else:
                self.__disp.set_terminator(length)

    def pack(self, format, *values):  # pylint: disable=W0622
        """Send a value."""

        self.__disp.push(ItemParser().parse(format).pack(*values))

    def handleClose(self):
        pass

    def handleNewObject(self, obj):
        raise NotImplementedError

    def finished(self):
        raise NotImplementedError

###############################################################################
# Actual protocol

_PROTOVERSION = 5


class IPhoneHandler(Protocol):
    def __init__(self):
        self.state = None
        self.__buffer = ''
        self.__expecting = None
        random.seed(time.time())

    def connectionMade(self):
        self.transport.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        self.state = BaseState(self)
        self.state.setState(InitialState, _PROTOVERSION)

    def log(self, msg, *args):
        if self.state.ui is not None:
            self.state.ui.AddLogLine(msg % args)

    def _flush(self):
        while self.__expecting is not None and len(self.__buffer) >= self.__expecting:
            data = self.__buffer[:self.__expecting]
            self.__buffer = self.__buffer[self.__expecting:]
            self.state.collect_incoming_data(data)
            self.state.found_terminator()

    def set_terminator(self, terminator):
        self.__expecting = terminator
        self._flush()

    def close_when_done(self):
        # XXX: without this delay, the other side sometimes doesn't "notice" the socket has been
        # closed... I should take a look with Wireshark...
        from twisted.internet import reactor
        reactor.callLater(0.5, self.transport.loseConnection)

    def dataReceived(self, data):
        self.__buffer += data
        self._flush()

    def connectionLost(self, reason):
        self.state.handleClose()

    def push(self, data):
        self.transport.write(data)


class IPhoneAcceptor(ServerFactory):
    protocol = IPhoneHandler

    def __init__(self, window, settings, iocontroller):
        from twisted.internet import reactor

        self.window = window
        self.settings = settings
        self.iocontroller = iocontroller

        for port in xrange(4096, 8192):
            try:
                self.__listening = reactor.listenTCP(port, self, backlog=5)
            except CannotListenError:
                pass
            else:
                break
        else:
            raise RuntimeError('Could not find a port to bind to.')

        self.port = port

    def buildProtocol(self, addr):
        password = self.settings.get('iphone', 'password')
        if password:
            protocol = ServerFactory.buildProtocol(self, addr)
            protocol.window = self.window
            protocol.settings = self.settings
            protocol.iocontroller = self.iocontroller
            return protocol

        wx.MessageBox(_('''An iPhone or iPod Touch tried to connect to Task Coach,\n'''
                        '''but no password is set. Please set a password in the\n'''
                        '''iPhone section of the configuration and try again.'''),
                        _('Error'), wx.OK)

        return None

    def close(self):
        self.__listening.stopListening()
        self.__listening = None


class BaseState(State): # pylint: disable=W0223
    def __init__(self, disp, *args, **kwargs):
        self.oldTasks = disp.window.taskFile.tasks().copy()
        self.oldCategories = disp.window.taskFile.categories().copy()

        self.ui = None

        self.syncCompleted = disp.settings.getboolean('iphone', 'synccompleted')

        super(BaseState, self).__init__(disp, *args, **kwargs)

    def isTaskEligible(self, task):
        """Returns True if a task should be considered when syncing with an iPhone/iPod Touch
        device. Right now, a task is eligible if

         * It's a leaf task (no children)
         * Or it has a reminder
         * Or it's overdue
         * Or it belongs to a category named 'iPhone'

         This will probably be more configurable in the future."""

        if task.completed() and not self.syncCompleted:
            return False

        if task.isDeleted():
            return False

        if len(task.children()) == 0:
            return True

        if task.reminder() is not None:
            return True

        if task.overdue():
            return True

        for category in task.categories():
            if category.subject() == 'iPhone':
                return True

        return False

    def handleClose(self):
        if self.ui is not None:
            self.ui.Finished()

        # Rollback
        self.disp().window.restoreTasks(self.oldCategories, self.oldTasks)


class InitialState(BaseState):
    def init(self, version):
        self.version = version

        super(InitialState, self).init('i', 1)

        if self.version == _PROTOVERSION:
            self.ui = self.disp().window.createIPhoneProgressFrame()
            self.ui.Started()

        self.pack('i', version)

    def handleNewObject(self, accepted):
        if accepted:
            self.disp().log(_('Protocol version: %d'), self.version)
            self.setState(PasswordState)
        else:
            if self.version == 1:
                # Do not close the connection because it causes an error on the
                # device. It will do it itself.
                self.disp().window.notifyIPhoneProtocolFailed()
            else:
                self.disp().log(_('Rejected protocol version %d'), self.version)
                self.setState(InitialState, self.version - 1)

    def finished(self):
        pass


class PasswordState(BaseState):
    def init(self):
        super(PasswordState, self).init('20b', 1)

        self.hashData = ''.join([struct.pack('B', random.randint(0, 255)) for dummy in xrange(512)])
        self.pack('20b', self.hashData)

    def handleNewObject(self, hash): # pylint: disable=W0622
        local = hashlib.sha1()
        local.update(self.hashData + self.disp().settings.get('iphone', 'password').encode('UTF-8'))

        if hash == local.digest():
            self.disp().log(_('Hash OK.'))
            self.pack('i', 1)
            self.setState(DeviceNameState)
        else:
            self.disp().log(_('Hash KO.'))
            self.pack('i', 0)
            self.setState(PasswordState)

    def finished(self):
        pass


class DeviceNameState(BaseState):
    def init(self):
        super(DeviceNameState, self).init('s', 1)

    def handleNewObject(self, name):
        self.disp().log(_('Device name: %s'), name)
        self.deviceName = name
        self.ui.SetDeviceName(name)
        self.setState(GUIDState)


class GUIDState(BaseState):
    def init(self):
        if self.version >= 4:
            super(GUIDState, self).init('i', 1)
            self.pack('s', self.disp().window.taskFile.guid())
        else:
            super(GUIDState, self).init('z', 1)

    def handleNewObject(self, guid):
        self.disp().log(_('GUID: %s'), guid)

        if self.version >= 4:
            self.setState(TaskFileNameState)
        else:
            type_ = self.disp().window.getIPhoneSyncType(guid)

            self.pack('i', type_)

            if type_ == 0:
                self.setState(TwoWayState)
            elif type_ == 1:
                self.setState(FullFromDesktopState)
            elif type_ == 2:
                self.setState(FullFromDeviceState)

            # On cancel, the other end will close the connection

    def finished(self):
        pass


class TaskFileNameState(BaseState):
    def init(self):
        super(TaskFileNameState, self).init('i', 1)

        filename = self.disp().iocontroller.filename()
        if filename:
            filename = os.path.splitext(os.path.split(filename)[1])[0]
        self.disp().log(_('Sending file name: %s'), filename)
        self.pack('z', filename)

    def handleNewObject(self, response): # pylint: disable=W0613
        self.setState(TwoWayState if self.version < 5 else DayHoursState)
        
    def finished(self):
        pass


class DayHoursState(BaseState):
    def init(self):
        super(DayHoursState, self).init('i', 1)

        self.pack('ii',
                  self.disp().settings.getint('view', 'efforthourstart'),
                  self.disp().settings.getint('view', 'efforthourend'))

    def handleNewObject(self, response): # pylint: disable=W0613
        self.setState(TwoWayState)

    def finished(self):
        pass


class FullFromDesktopState(BaseState):
    def init(self):
        self.disp().log(_('Full from desktop.'))

        if self.version >= 4:
            allEfforts = self.disp().window.taskFile.efforts()

            if self.syncCompleted:
                self.tasks = list([task for task in self.disp().window.taskFile.tasks().allItemsSorted() if not task.isDeleted()])
                self.efforts = list([effort for effort in  allEfforts \
                                  if effort.task() is None or not effort.task().isDeleted()])
            else:
                self.tasks = list([task for task in self.disp().window.taskFile.tasks().allItemsSorted() if not (task.isDeleted() or task.completed())])
                self.efforts = list([effort for effort in allEfforts \
                                  if effort.task() is None or not (effort.task().isDeleted() or effort.task().completed())])
        else:
            self.tasks = filter(self.isTaskEligible, self.disp().window.taskFile.tasks()) # pylint: disable=W0141
        self.categories = list([cat for cat in self.disp().window.taskFile.categories().allItemsSorted() if not cat.isDeleted()])

        if self.version >= 4:
            self.pack('iii', len(self.categories), len(self.tasks), len(self.efforts))
            self.total = len(self.categories) + len(self.tasks) + len(self.efforts)
        else:
            self.pack('ii', len(self.categories), len(self.tasks))
            self.total = len(self.categories) + len(self.tasks)

        self.count = 0

        self.setState(FullFromDesktopCategoryState)


class FullFromDesktopCategoryState(BaseState):
    def init(self):
        super(FullFromDesktopCategoryState, self).init('i', len(self.categories))

        self.disp().log(_('%d categories'), len(self.categories))

        if self.categories:
            self.sendObject()

    def sendObject(self):
        if self.categories:
            category = self.categories.pop(0)
            self.disp().log(_('Send category %s'), category.id())
            self.pack('ssz', category.subject(), category.id(),
                      None if category.parent() is None else category.parent().id())

    def handleNewObject(self, code):
        self.disp().log(_('Response: %d'), code)
        self.count += 1
        self.ui.SetProgress(self.count, self.total)
        self.sendObject()

    def finished(self):
        self.setState(FullFromDesktopTaskState)


class FullFromDesktopTaskState(BaseState):
    def init(self):
        super(FullFromDesktopTaskState, self).init('i', len(self.tasks))

        self.disp().log(_('%d tasks'), len(self.tasks))

        if self.tasks:
            self.sendObject()

    def sendObject(self):
        if self.tasks:
            task = self.tasks.pop(0)
            self.disp().log(_('Send task %s'), task.id())
            if self.version < 4:
                self.pack('sssddd[s]',
                          task.subject(),
                          task.id(),
                          task.description(),
                          task.plannedStartDateTime().date(),
                          task.dueDateTime().date(),
                          task.completionDateTime().date(),
                          [category.id() for category in task.categories()])
            elif self.version < 5:
                self.pack('sssdddz[s]',
                          task.subject(),
                          task.id(),
                          task.description(),
                          task.plannedStartDateTime().date(),
                          task.dueDateTime().date(),
                          task.completionDateTime().date(),
                          task.parent().id() if task.parent() is not None else None,
                          [category.id() for category in task.categories()])
            else:
                hasRecurrence = task.recurrence() is not None and task.recurrence().unit != ''
                if hasRecurrence:
                    recPeriod = {'daily': 0, 'weekly': 1, 'monthly': 2, 'yearly': 3}[task.recurrence().unit]
                    recRepeat = task.recurrence().amount
                    recSameWeekday = task.recurrence().sameWeekday
                else:
                    recPeriod = 0
                    recRepeat = 0
                    recSameWeekday = 0

                self.pack('sssffffziiiii[s]',
                          task.subject(),
                          task.id(),
                          task.description(),
                          task.plannedStartDateTime(),
                          task.dueDateTime(),
                          task.completionDateTime(),
                          task.reminder(),
                          task.parent().id() if task.parent() is not None else None,
                          task.priority(),
                          hasRecurrence,
                          recPeriod,
                          recRepeat,
                          recSameWeekday,
                          [category.id() for category in task.categories()])

    def handleNewObject(self, code):
        self.disp().log(_('Response: %d'), code)
        self.count += 1
        self.ui.SetProgress(self.count, self.total)
        self.sendObject()

    def finished(self):
        if self.version >= 4:
            self.setState(FullFromDesktopEffortState)
        else:
            self.setState(SendGUIDState)


class FullFromDesktopEffortState(BaseState):
    def init(self):
        super(FullFromDesktopEffortState, self).init('i', len(self.efforts))

        self.disp().log(_('%d efforts'), len(self.efforts))

        if self.efforts:
            self.sendObject()

    def sendObject(self):
        if self.efforts:
            effort = self.efforts.pop(0)
            self.disp().log(_('Send effort %s'), effort.id())
            self.pack('ssztt',
                      effort.id(),
                      effort.subject(),
                      effort.task().id() if effort.task() is not None else None,
                      effort.getStart(),
                      effort.getStop())

    def handleNewObject(self, code): # pylint: disable=W0613
        self.count += 1
        self.ui.SetProgress(self.count, self.total)
        self.sendObject()

    def finished(self):
        if self.version < 5:
            self.setState(SendGUIDState)
        else:
            self.disp().log(_('Finished.'))
            self.disp().close_when_done()
            self.ui.Finished()

    def handleClose(self):
        if self.version < 5:
            super(FullFromDesktopEffortState, self).handleClose()


class FullFromDeviceState(BaseState):
    def init(self):
        self.disp().window.clearTasks()

        super(FullFromDeviceState, self).init('ii', 1)

    def handleNewObject(self, (categoryCount, taskCount)):
        self.categoryCount = categoryCount
        self.taskCount = taskCount

        self.total = categoryCount + taskCount
        self.count = 0

        self.setState(FullFromDeviceCategoryState)

    def finished(self):
        pass


class FullFromDeviceCategoryState(BaseState):
    def init(self):
        self.categoryMap = {}

        super(FullFromDeviceCategoryState, self).init('s' if self.version < 3 else 'sz', self.categoryCount)

    def handleNewObject(self, args):
        if self.version < 3:
            name = args
            parentId = None
        else:
            name, parentId = args

        if parentId is None:
            category = Category(name)
        else:
            category = self.categoryMap[parentId].newChild(name)

        self.disp().window.addIPhoneCategory(category)

        self.pack('s', category.id())
        self.categoryMap[category.id()] = category

        self.count += 1
        self.ui.SetProgress(self.count, self.total)

    def finished(self):
        self.setState(FullFromDeviceTaskState)


class FullFromDeviceTaskState(BaseState):
    def init(self):
        super(FullFromDeviceTaskState, self).init('ssddd[s]', self.taskCount)

    def handleNewObject(self, (subject, description, startDate, dueDate, completionDate, categories)):
        task = Task(subject=subject, description=description, 
                    plannedStartDateTime=DateTime(startDate.year, startDate.month, startDate.day),
                    dueDateTime=DateTime(dueDate.year, dueDate.month, dueDate.day), 
                    completionDateTime=DateTime(completionDate.year, completionDate.month, completionDate.day))

        self.disp().window.addIPhoneTask(task, [self.categoryMap[id_] for id_ in categories])

        self.count += 1
        self.ui.SetProgress(self.count, self.total)

        self.pack('s', task.id())

    def finished(self):
        self.setState(SendGUIDState)


class TwoWayState(BaseState):
    def init(self):
        self.categoryMap = dict([(category.id(), category) for category in self.disp().window.taskFile.categories()])
        self.taskMap = dict([(task.id(), task) for task in self.disp().window.taskFile.tasks()])
        self.effortMap = dict([(effort.id(), effort) for effort in self.disp().window.taskFile.efforts()])

        if self.version < 3:
            super(TwoWayState, self).init('iiii', 1)
        elif self.version < 4:
            super(TwoWayState, self).init('iiiiii', 1)
        else:
            super(TwoWayState, self).init('iiiiiiiii', 1)

    def handleNewObject(self, args):
        if self.version < 3:
            (self.newCategoriesCount,
             self.newTasksCount,
             self.deletedTasksCount,
             self.modifiedTasksCount) = args
        elif self.version < 4:
            (self.newCategoriesCount,
             self.newTasksCount,
             self.deletedTasksCount,
             self.modifiedTasksCount,
             self.deletedCategoriesCount,
             self.modifiedCategoriesCount) = args
        else:
            (self.newCategoriesCount,
             self.newTasksCount,
             self.deletedTasksCount,
             self.modifiedTasksCount,
             self.deletedCategoriesCount,
             self.modifiedCategoriesCount,
             self.newEffortsCount,
             self.modifiedEffortsCount,
             self.deletedEffortsCount) = args

            self.disp().log(_('%d new categories'), self.newCategoriesCount)
            self.disp().log(_('%d new tasks'), self.newTasksCount)
            self.disp().log(_('%d new efforts'), self.newEffortsCount)
            self.disp().log(_('%d modified categories'), self.modifiedCategoriesCount)
            self.disp().log(_('%d modified tasks'), self.modifiedTasksCount)
            self.disp().log(_('%d modified efforts'), self.modifiedEffortsCount)
            self.disp().log(_('%d deleted categories'), self.deletedCategoriesCount)
            self.disp().log(_('%d deleted tasks'), self.deletedTasksCount)
            self.disp().log(_('%d deleted efforts'), self.deletedEffortsCount)

        self.setState(TwoWayNewCategoriesState)


class TwoWayNewCategoriesState(BaseState):
    def init(self):
        super(TwoWayNewCategoriesState, self).init(('s' if self.version < 3 else 'sz'), self.newCategoriesCount)

    def handleNewObject(self, args):
        if self.version < 3:
            name = args
            parentId = None
        else:
            name, parentId = args
            self.disp().log(_('New category (parent: %s)'), parentId)

        if parentId is None or not self.categoryMap.has_key(parentId):
            category = Category(name)
        else:
            category = self.categoryMap[parentId].newChild(name)

        self.disp().window.addIPhoneCategory(category)

        self.categoryMap[category.id()] = category
        self.pack('s', category.id())

    def finished(self):
        if self.version < 3:
            self.setState(TwoWayNewTasksState)
        else:
            self.setState(TwoWayDeletedCategoriesState)


class TwoWayDeletedCategoriesState(BaseState):
    def init(self):
        super(TwoWayDeletedCategoriesState, self).init('s', self.deletedCategoriesCount)

    def handleNewObject(self, catId):
        try:
            category = self.categoryMap.pop(catId)
        except KeyError:
            # Deleted on desktop
            if self.version >= 5:
                self.pack('s', '')
        else:
            self.disp().log(_('Delete category %s'), category.id())
            if self.version >= 5:
                self.pack('s', category.id())
            self.disp().window.removeIPhoneCategory(category)

    def finished(self):
        self.setState(TwoWayModifiedCategoriesState)


class TwoWayModifiedCategoriesState(BaseState):
    def init(self):
        super(TwoWayModifiedCategoriesState, self).init('ss', self.modifiedCategoriesCount)

    def handleNewObject(self, (name, catId)):
        try:
            category = self.categoryMap[catId]
        except KeyError:
            if self.version >= 5:
                self.pack('s', '')
        else:
            self.disp().log(_('Modify category %s'), category.id())
            self.disp().window.modifyIPhoneCategory(category, name)

            if self.version >= 5:
                self.pack('s', category.id())

    def finished(self):
        if self.version < 4:
            self.setState(TwoWayNewTasksState)
        elif self.version < 5:
            self.setState(TwoWayNewTasksState4)
        else:
            self.setState(TwoWayNewTasksState5)


class TwoWayNewTasksState(BaseState):
    def init(self):
        super(TwoWayNewTasksState, self).init('ssddd[s]', self.newTasksCount)

    def handleNewObject(self, (subject, description, startDate, dueDate, completionDate, categories)):
        task = Task(subject=subject, description=description, 
                    plannedStartDateTime=DateTime(startDate.year, startDate.month, startDate.day),
                    dueDateTime=DateTime(dueDate.year, dueDate.month, dueDate.day), 
                    completionDateTime=DateTime(completionDate.year, completionDate.month, completionDate.day))

        self.disp().window.addIPhoneTask(task, [self.categoryMap[catId] for catId in categories \
                                                    if self.categoryMap.has_key(catId)])
        self.disp().log(_('New task %s'), task.id())

        self.taskMap[task.id()] = task
        self.pack('s', task.id())

    def finished(self):
        self.setState(TwoWayDeletedTasksState)


class TwoWayNewTasksState4(BaseState):
    def init(self):
        super(TwoWayNewTasksState4, self).init('ssddfz[s]', self.newTasksCount)

    def handleNewObject(self, (subject, description, plannedStartDate, dueDate, completionDateTime, parentId, categories)):
        parent = self.taskMap[parentId] if parentId and self.taskMap.has_key(parentId) else None

        if self.version < 5:
            plannedStartDateTime = DateTime() if plannedStartDate == Date() else \
                DateTime(year=plannedStartDate.year, month=plannedStartDate.month,
                         day=plannedStartDate.day, hour=self.disp().settings.getint('view', 'efforthourstart'))

            dueDateTime = DateTime() if dueDate == Date() else \
                DateTime(year=dueDate.year, month=dueDate.month, day=dueDate.day,
                         hour=self.disp().settings.getint('view', 'efforthourend'))

        task = Task(subject=subject, description=description, 
                    plannedStartDateTime=plannedStartDateTime,
                    dueDateTime=dueDateTime, 
                    completionDateTime=completionDateTime, 
                    parent=parent)

        self.disp().window.addIPhoneTask(task, [self.categoryMap[catId] for catId in categories \
                                                    if self.categoryMap.has_key(catId)])
        self.disp().log(_('New task %s'), task.id())

        self.taskMap[task.id()] = task
        self.pack('s', task.id())

    def finished(self):
        self.setState(TwoWayDeletedTasksState)


class TwoWayNewTasksState5(BaseState):
    def init(self):
        super(TwoWayNewTasksState5, self).init('ssffffiiiiiz[s]', self.newTasksCount)

    def handleNewObject(self, (subject, description, plannedStartDateTime, dueDateTime, completionDateTime,
                               reminderDateTime, priority, hasRecurrence, recPeriod, recRepeat,
                               recSameWeekday, parentId, categories)):
        parent = self.taskMap[parentId] if parentId else None

        recurrence = None
        if hasRecurrence:
            recurrence = Recurrence(unit={0: 'daily', 1: 'weekly', 2: 'monthly', 3: 'yearly'}[recPeriod],
                                    amount=recRepeat, sameWeekday=recSameWeekday)

        task = Task(subject=subject, description=description, 
                    plannedStartDateTime=plannedStartDateTime,
                    dueDateTime=dueDateTime, 
                    completionDateTime=completionDateTime, 
                    parent=parent,
                    recurrence=recurrence,
                    priority=priority)

        # Don't start a timer from this thread...
        wx.CallAfter(task.setReminder, reminderDateTime)

        self.disp().window.addIPhoneTask(task, [self.categoryMap[catId] for catId in categories \
                                                    if self.categoryMap.has_key(catId)])
        self.disp().log(_('New task %s'), task.id())

        self.taskMap[task.id()] = task
        self.pack('s', task.id())

    def finished(self):
        self.setState(TwoWayDeletedTasksState)


class TwoWayDeletedTasksState(BaseState):
    def init(self):
        super(TwoWayDeletedTasksState, self).init('s', self.deletedTasksCount)

    def handleNewObject(self, taskId):
        try:
            task = self.taskMap.pop(taskId)
        except KeyError:
            if self.version >= 5:
                self.pack('s', '')
        else:
            self.disp().log(_('Delete task %s'), task.id())
            if self.version >= 5:
                self.pack('s', task.id())
            self.disp().window.removeIPhoneTask(task)

    def finished(self):
        self.setState(TwoWayModifiedTasks)


class TwoWayModifiedTasks(BaseState):
    def init(self):
        if self.version < 2:
            super(TwoWayModifiedTasks, self).init('sssddd', self.modifiedTasksCount)
        elif self.version < 5:
            super(TwoWayModifiedTasks, self).init('sssddd[s]', self.modifiedTasksCount)
        else:
            super(TwoWayModifiedTasks, self).init('sssffffiiiii[s]', self.modifiedTasksCount)

    def handleNewObject(self, args):
        reminderDateTime = None
        recurrence = None
        priority = 0

        if self.version < 2:
            subject, taskId, description, plannedStartDate, dueDate, completionDate = args
            categories = None
        elif self.version < 5:
            subject, taskId, description, plannedStartDate, dueDate, completionDate, categories = args
            categories = set([self.categoryMap[catId] for catId in categories])
        else:
            (subject, taskId, description, plannedStartDate, dueDate, completionDate, reminderDateTime,
             priority, hasRecurrence, recPeriod, recRepeat, recSameWeekday, categories) = args
            categories = set([self.categoryMap[catId] for catId in categories if catId in self.categoryMap])

            if hasRecurrence:
                recurrence = Recurrence(unit={0: 'daily', 1: 'weekly', 2: 'monthly', 3: 'yearly'}[recPeriod],
                                        amount=recRepeat, sameWeekday=recSameWeekday)

        if self.version < 5:
            plannedStartDateTime = DateTime(plannedStartDate.year, plannedStartDate.month, plannedStartDate.day,
                self.disp().settings.getint('view', 'efforthourstart')) if plannedStartDate != Date() else DateTime()
            dueDateTime = DateTime(dueDate.year, dueDate.month, dueDate.day,
                self.disp().settings.getint('view', 'efforthourend')) if dueDate != Date() else DateTime()
            completionDateTime = DateTime(completionDate.year, completionDate.month, 
                completionDate.day) if completionDate != Date() else DateTime()
        else:
            plannedStartDateTime = plannedStartDate
            dueDateTime = dueDate
            completionDateTime = completionDate

        try:
            task = self.taskMap[taskId]
        except KeyError:
            if self.version >= 5:
                self.pack('s', '')
        else:
            self.disp().log(_('Modify task %s'), task.id())
            self.disp().window.modifyIPhoneTask(task, subject, description, 
                                                plannedStartDateTime, dueDateTime, 
                                                completionDateTime, reminderDateTime,
                                                recurrence, priority, categories)
            if self.version >= 5:
                self.pack('s', task.id())

    def finished(self):
        self.disp().log(_('End of task synchronization.'))
        if self.version < 4:
            self.setState(FullFromDesktopState)
        else:
            self.setState(TwoWayNewEffortsState)


class TwoWayNewEffortsState(BaseState):
    def init(self):
        super(TwoWayNewEffortsState, self).init('sztt', self.newEffortsCount)

    def handleNewObject(self, (subject, taskId, started, ended)):
        task = None
        if taskId is not None:
            try:
                task = self.taskMap[taskId]
            except KeyError:
                self.disp().log(_('Could not find task %s for effort.'), taskId)

        effort = Effort(task, started, ended, subject=subject)
        self.disp().log(_('New effort %s'), effort.id())
        self.disp().window.addIPhoneEffort(task, effort)

        self.pack('s', effort.id())

        self.effortMap[effort.id()] = effort

    def finished(self):
        self.setState(TwoWayModifiedEffortsState)


class TwoWayModifiedEffortsState(BaseState):
    def init(self):
        super(TwoWayModifiedEffortsState, self).init('sstt', self.modifiedEffortsCount)

    def handleNewObject(self, (id_, subject, started, ended)):
        # Actually, the taskId cannot be modified on the device, which saves
        # us some headaches.

        try:
            effort = self.effortMap[id_]
        except KeyError:
            if self.version >= 5:
                self.pack('s', '')
        else:
            self.disp().log(_('Modify effort %s'), effort.id())
            self.disp().window.modifyIPhoneEffort(effort, subject, started, ended)
            if self.version >= 5:
                self.pack('s', effort.id())

    def finished(self):
        # Efforts cannot be deleted on the iPhone yet.
        self.setState(FullFromDesktopState)


class SendGUIDState(BaseState):
    def init(self):
        super(SendGUIDState, self).init('i', 1)

        self.disp().log(_('Sending GUID: %s'), self.disp().window.taskFile.guid())
        self.pack('s', self.disp().window.taskFile.guid())

    def handleNewObject(self, code):
        pass

    def finished(self):
        self.disp().log(_('Finished.'))
        self.disp().close_when_done()
        self.ui.Finished()

    def handleClose(self):
        pass