~ehmry/nim_tox

ref: 3b6a3ca028805d88f4e7bc634ab2327bd9a1ebf1 nim_tox/src/toxcore.nim -rw-r--r-- 51.8 KiB
3b6a3ca0Emery Hemingway New boostrap JSON format 8 months ago
                                                                                
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
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
# SPDX-FileCopyrightText: 2019 Emery Hemingway
# SPDX-License-Identifier: GPL-3.0-or-later

import std/strutils

{.passC: staticExec("pkg-config --cflags toxcore").}
{.passL: staticExec("pkg-config --libs toxcore").}

{.pragma: ctoxHeader, header: "tox/tox.h".}
{.pragma: ctoxEnum, ctoxHeader, importc: "Tox_$1".}
{.pragma: ctoxProc, ctoxHeader, importc: "tox_$1".}
{.pragma: ctoxCallbackProc, ctoxHeader, importc: "tox_callback_$1".}

type ToxError* = object of CatchableError

template ctoxAssert(good, value: untyped) =
  if value != good: raise newException(ToxError, $value)

proc ctoxString(buf: ptr uint8; len: csize): string =
  ## Copy a buffer from the core to a Nim string.
  if 0 < len:
    result = newString(len)
    copyMem(addr result[0], buf, result.len)
  else:
    result = ""

proc ctoxArray[T](buf: ptr uint8): T =
  ## Copy a fixed-length buffer from the core to an array object.
  copyMem(addr result.bytes[0], buf, T.bytes.len)

const # Values converted from tox.h defines
  TOX_PUBLIC_KEY_SIZE = 32
  TOX_SECRET_KEY_SIZE = 32
  TOX_CONFERENCE_UID_SIZE = 32
  TOX_CONFERENCE_ID_SIZE = 32
  TOX_NOSPAM_SIZE = (sizeof((uint32)))
  TOX_ADDRESS_SIZE = (TOX_PUBLIC_KEY_SIZE + TOX_NOSPAM_SIZE + sizeof((uint16)))
  TOX_MAX_NAME_LENGTH = 128
  TOX_MAX_STATUS_MESSAGE_LENGTH = 1007
  TOX_MAX_FRIEND_REQUEST_LENGTH = 1016
  TOX_MAX_MESSAGE_LENGTH = 1372
  TOX_MAX_CUSTOM_PACKET_SIZE = 1373
  TOX_HASH_LENGTH = 32
  TOX_FILE_ID_LENGTH = 32
  TOX_MAX_FILENAME_LENGTH = 255
  TOX_MAX_HOSTNAME_LENGTH = 255

func version_major*(): uint32 {.ctoxProc.}
func version_minor*(): uint32 {.ctoxProc.}
func version_patch*(): uint32 {.ctoxProc.}
func version_is_compatible*(major, minor, patch: uint32): bool {.ctoxProc.}
func version_is_compatible*(): bool {.importc:
  "TOX_VERSION_IS_ABI_COMPATIBLE", ctoxHeader.}

func public_key_size(): uint32 {.ctoxProc.}
func secret_key_size(): uint32 {.ctoxProc.}
func conference_uid_size(): uint32 {.ctoxProc.}
func conference_id_size(): uint32 {.ctoxProc.}
func nospam_size(): uint32 {.ctoxProc.}
func address_size(): uint32 {.ctoxProc.}
func max_name_length(): uint32 {.ctoxProc.}
func max_status_message_length(): uint32 {.ctoxProc.}
func max_friend_request_length(): uint32 {.ctoxProc.}
func max_message_length(): uint32 {.ctoxProc.}
func max_custom_packet_size(): uint32 {.ctoxProc.}
func hash_length(): uint32 {.ctoxProc.}
func file_id_length(): uint32 {.ctoxProc.}
func max_filename_length(): uint32 {.ctoxProc.}
func max_hostname_length(): uint32 {.ctoxProc.}

# Validate that the ABI is consistent
assert(TOX_PUBLIC_KEY_SIZE == (int)public_key_size())
assert(TOX_SECRET_KEY_SIZE == (int)secret_key_size())
assert(TOX_CONFERENCE_UID_SIZE == (int)conference_uid_size())
assert(TOX_CONFERENCE_ID_SIZE == (int)conference_id_size())
assert(TOX_NOSPAM_SIZE == (int)nospam_size())
assert(TOX_ADDRESS_SIZE == (int)address_size())
assert(TOX_MAX_NAME_LENGTH == (int)max_name_length())
assert(TOX_MAX_STATUS_MESSAGE_LENGTH == (int)max_status_message_length())
assert(TOX_MAX_FRIEND_REQUEST_LENGTH == (int)max_friend_request_length())
assert(TOX_MAX_MESSAGE_LENGTH == (int)max_message_length())
assert(TOX_MAX_CUSTOM_PACKET_SIZE == (int)max_custom_packet_size())
assert(TOX_HASH_LENGTH == (int)hash_length())
assert(TOX_FILE_ID_LENGTH == (int)file_id_length())
assert(TOX_MAX_FILENAME_LENGTH == (int)max_filename_length())
assert(TOX_MAX_HOSTNAME_LENGTH == (int)max_hostname_length())

template toxArrayType(T, N: untyped) =
  ## Generate an array type definition with hex conversions.
  type T* = object
    bytes*: array[N, uint8]
  func `$`*(x: T): string =
    result = newStringOfCap(N*2)
    for b in x.bytes:
      result.add b.toHex
  func `to T`*(s: string): T =
    doAssert(s.len == N*2)
    let raw = parseHexStr s
    for i in 0..<N:
      result.bytes[i] = (uint8)raw[i]

toxArrayType(PublicKey, TOX_PUBLIC_KEY_SIZE)
toxArrayType(SecretKey, TOX_SECRET_KEY_SIZE)
toxArrayType(Address, TOX_ADDRESS_SIZE)
toxArrayType(Hash, TOX_HASH_LENGTH)
toxArrayType(ConferenceId, TOX_CONFERENCE_ID_SIZE)
toxArrayType(ConferenceUid, TOX_CONFERENCE_UID_SIZE)

func publicKey*(id: Address): Publickey =
  ## Extract the public key from a Tox address.
  for i in 0..<TOX_PUBLIC_KEY_SIZE:
    result.bytes[i] = id.bytes[i]

func isValid*(id: Address): bool =
  ## Verify a Tox address using the footer checksum.
  var even, odd: uint8
  for i in countup(0, id.bytes.high, 2):
    even = even xor id.bytes[i]
  for i in countup(1, id.bytes.high, 2):
    odd = odd xor id.bytes[i]
  (even or odd) == 0

template toxIndexType(T: untyped) =
  ## Generate a index type definition with equality comparison.
  type T* = distinct uint32
  proc `==`*(x, y: T): bool {.borrow.}

toxIndexType Friend
toxIndexType NoSpam
toxIndexType MessageId
toxIndexType FileTransfer
toxIndexType Conference
toxIndexType Peer

type
  Connection* {.ctoxEnum.} = enum
    ## Connection state.
    TOX_CONNECTION_NONE,
    TOX_CONNECTION_TCP,
    TOX_CONNECTION_UDP

  User_Status* {.ctoxEnum.} = enum
    ## User status.
    TOX_USER_STATUS_NONE,
    TOX_USER_STATUS_AWAY,
    TOX_USER_STATUS_BUSY

  Message_Type* {.ctoxEnum.} = enum
    ## Application message type.
    TOX_MESSAGE_TYPE_NORMAL,
    TOX_MESSAGE_TYPE_ACTION

  Proxy_Type* {.ctoxEnum.} = enum
    ## Connection proxy method.
    TOX_PROXY_TYPE_NONE,
    TOX_PROXY_TYPE_HTTP,
    TOX_PROXY_TYPE_SOCKS5

  Savedata_Type* {.ctoxEnum.} = enum
    ## Format of save data.
    TOX_SAVEDATA_TYPE_NONE,
    TOX_SAVEDATA_TYPE_TOX_SAVE,
    TOX_SAVEDATA_TYPE_SECRET_KEY

  Log_Level* {.ctoxEnum.} = enum
    ## Logging level.
    TOX_LOG_LEVEL_TRACE,
    TOX_LOG_LEVEL_DEBUG,
    TOX_LOG_LEVEL_INFO,
    TOX_LOG_LEVEL_WARNING,
    TOX_LOG_LEVEL_ERROR

  File_Kind* {.ctoxEnum.} = enum
    ## File transfer type.
    TOX_FILE_KIND_DATA,
    TOX_FILE_KIND_AVATAR

  File_Control* {.ctoxEnum.} = enum
    ## File transfer control command.
    TOX_FILE_CONTROL_RESUME,
    TOX_FILE_CONTROL_PAUSE,
    TOX_FILE_CONTROL_CANCEL

  Conference_Type* {.ctoxEnum.} = enum
    ## Conference type.
    TOX_CONFERENCE_TYPE_TEXT,
    TOX_CONFERENCE_TYPE_AV

type
  Core* = distinct pointer
    ## Opaque C type wrapped by the `Tox` object.

  tox_log_cb* = proc (
    core: Core; level: Log_Level; file: cstring; line: uint32;
    `func`: cstring; message: cstring; user_data: pointer) {.cdecl.}
    ## Logging callback type invoked directly by C library.

  CbSelfConnectionStatus* = proc (
    status: Connection) {.closure, gcsafe.}

  CbFriendName* = proc (
    friend: Friend; name: string) {.gcsafe.}
  CbFriendStatusMessage* = proc (
    friend: Friend; msg: string) {.gcsafe.}
  CbFriendStatus* = proc (
    friend: Friend; status: UserStatus) {.gcsafe.}
  CbFriendConnectionStatus* = proc (
    friend: Friend; status: Connection) {.gcsafe.}
  CbFriendTyping* = proc (
    friend: Friend; typing: bool) {.gcsafe.}
  CbFriendReadReceipt* = proc (
    friend: Friend; id: MessageId) {.gcsafe.}
  CbFriendRequest* = proc (
    key: PublicKey; msg: string) {.gcsafe.}
  CbFriendMessage* = proc (
    friend: Friend; msg: string; kind: MessageType) {.gcsafe.}

  CbFileRecvControl* = proc (
    friend: Friend; file: FileTransfer; control: FileControl) {.gcsafe.}
  CbFileChunkRequest* = proc (
    friend: Friend; file: FileTransfer; pos: uint64; size: int) {.gcsafe.}
  CbFileRecv* = proc (
    friend: Friend; file: FileTransfer; kind: uint32; size: uint64;
        filename: string) {.gcsafe.}
  CbFileRecvChunk* = proc (
    friend: Friend; file: FileTransfer; pos: uint64; data: pointer;
        size: int) {.gcsafe.}

  CbConferenceInvite* = proc (
    friend: Friend; kind: ConferenceType; cookie: string) {.gcsafe.}
  CbConferenceConnected* = proc (
    conf: Conference) {.gcsafe.}
  CbConferenceMessage* = proc (
    conf: Conference; peer: Peer; kind: MessageType; msg: string) {.gcsafe.}
  CbConferenceTitle* = proc (
    conf: Conference; peer: Peer; title: string) {.gcsafe.}
  CbConferencePeerName* = proc (
    conf: Conference; peer: Peer; name: string) {.gcsafe.}
  CbConferencePeerListChanged* = proc (
    conf: Conference) {.gcsafe.}
  CbFriendLossyPacket* = proc (
    friend: Friend; data: pointer; size: int) {.gcsafe.}
  CbFriendLosslessPacket* = proc (
    friend: Friend; data: pointer; size: int) {.gcsafe.}

  Tox* = ref object
    ## Tox instance.
    core*: Core
    selfConnectionStatus: CbSelfConnectionStatus
    friendName: CbFriendName
    friendStatusMessage: CbFriendStatusMessage
    friendStatus: CbFriendStatus
    friendConnectionStatus: CbFriendConnectionStatus
    friendTyping: CbFriendTyping
    friendReadReceipt: CbFriendReadReceipt
    friendRequest: CbFriendRequest
    friendMessage: CbFriendMessage
    fileRecvControl: CbFileRecvControl
    fileChunkRequest: CbFileChunkRequest
    fileRecv: CbFileRecv
    fileRecvChunk: CbFileRecvChunk
    conferenceInvite: CbConferenceInvite
    conferenceConnected: CbConferenceConnected
    conferenceMessage: CbConferenceMessage
    conferenceTitle: CbConferenceTitle
    conferencePeerName: CbConferencePeerName
    conferencePeerListChanged: CbConferencePeerListChanged
    friendLossyPacket: CbFriendLossyPacket
    friendLosslessPacket: CbFriendLosslessPacket

type
  Tox_Options {.pure, importc: "struct Tox_Options".} = object
  Options* = ptr Tox_Options
    ## Object for initializing a Tox instance.

{.pragma: ctox_options, importc: "tox_options_$1", ctoxHeader.}
{.pragma: ctox_options_get, importc: "tox_options_get_$1", ctoxHeader.}

proc ipv6_enabled*(options: Options): bool {.ctox_options_get.}
proc `ipv6_enabled=`*(options: Options; ipv6_enabled: bool) {.
  importc: "tox_options_set_ipv6_enabled", ctoxHeader.}

proc udp_enabled*(options: Options): bool {.ctox_options_get.}
proc `udp_enabled=`*(options: Options; udp_enabled: bool) {.
  importc: "tox_options_set_udp_enabled", ctoxHeader.}

proc local_discovery_enabled*(options: Options): bool {.ctox_options_get.}
proc `local_discovery_enabled=`*(options: Options;
    local_discovery_enabled: bool) {.
  importc: "tox_options_set_local_discovery_enabled", ctoxHeader, ctoxHeader.}

proc proxy_type*(options: Options): ProxyType {.ctox_options_get.}
proc `proxy_type=`*(options: Options; `type`: ProxyType) {.
  importc: "tox_options_set_proxy_type", ctoxHeader.}

proc proxy_host*(options: Options): cstring {.ctox_options_get.}
proc `proxy_host=`*(options: Options; host: cstring) {.
  importc: "tox_options_set_proxy_host", ctoxHeader.}

proc proxy_port*(options: Options): uint16 {.ctox_options_get.}
proc `proxy_port=`*(options: Options; port: uint16) {.
  importc: "tox_options_set_proxy_port", ctoxHeader.}

proc start_port*(options: Options): uint16 {.ctox_options_get.}
proc `start_port=`*(options: Options; start_port: uint16) {.
  importc: "tox_options_set_start_port", ctoxHeader.}

proc end_port*(options: Options): uint16 {.ctox_options_get.}
proc `end_port=`*(options: Options; end_port: uint16) {.
  importc: "tox_options_set_end_port", ctoxHeader.}

proc tcp_port*(options: Options): uint16 {.ctox_options_get.}
proc `tcp_port=`*(options: Options; tcp_port: uint16) {.
  importc: "tox_options_set_tcp_port", ctoxHeader.}

proc hole_punching_enabled*(options: Options): bool {.ctox_options_get.}
proc `hole_punching_enabled=`*(options: Options; hole_punching_enabled: bool) {.
  importc: "tox_options_set_hole_punching_enabled", ctoxHeader.}

proc savedata_type*(options: Options): SavedataType {.ctox_options_get.}
proc `savedata_type=`*(options: Options; `type`: SavedataType) {.
  importc: "tox_options_set_savedata_type", ctoxHeader.}

proc savedata_data*(options: Options): ptr uint8 {.ctox_options_get.}
proc savedata_length*(options: Options): csize {.ctox_options_get.}

proc `saveData=`*(options: Options; data: string) =
  proc options_set_savedata_data(options: Options; data: cstring;
      length: csize) {.ctoxProc, ctoxHeader.}
  # proc options_set_savedata_length(options: Options; length: csize) {.ctoxProc, ctoxHeader.}
  options.options_set_savedata_data(data, data.len)

proc log_callback*(options: Options): tox_log_cb {.ctox_options_get.}
proc `log_callback=`*(options: Options; callback: tox_log_cb) {.
  importc: "tox_options_set_log_callback", ctoxHeader.}
  ## Install a logging callback within the C Tox core. This callback
  ## must have C calling convention and thus annotated with the
  ## {.cdecl, ctoxHeader.} pragma.

proc log_user_data*(options: Options): pointer {.ctox_options_get.}
proc `log_user_data=`*(options: Options; user_data: pointer) {.
  importc: "tox_options_set_log_user_data", ctoxHeader.}
  ## Set state object passed to logging callback.

type
  Err_Options_New {.ctoxEnum.} = enum
    TOX_ERR_OPTIONS_NEW_OK,
    TOX_ERR_OPTIONS_NEW_MALLOC
  Err_New {.ctoxEnum.} = enum
    TOX_ERR_NEW_OK,
    TOX_ERR_NEW_NULL,
    TOX_ERR_NEW_MALLOC,
    TOX_ERR_NEW_PORT_ALLOC,
    TOX_ERR_NEW_PROXY_BAD_TYPE,
    TOX_ERR_NEW_PROXY_BAD_HOST,
    TOX_ERR_NEW_PROXY_BAD_PORT,
    TOX_ERR_NEW_PROXY_NOT_FOUND,
    TOX_ERR_NEW_LOAD_ENCRYPTED,
    TOX_ERR_NEW_LOAD_BAD_FORMAT

proc tox_new(options: Options; error: ptr Err_New): Core {.
  importc, ctoxHeader.}

proc newTox*(configure: proc (opt: Options)): Tox =
  ## Create a new Tox instance.
  ##
  ## .. code-block:: nim
  ##   let tox = newTox do (opts: Options):
  ##     opts.localDiscoveryEnabled = true
  ##     opts.holePunchingEnabled = false
  ##  tox.iterate()
  ##
  proc options_new(error: ptr ERR_OPTIONS_NEW): Options {.ctoxProc.}
  proc options_default(options: Options) {.ctoxProc.}
  proc options_free(options: Options) {.ctoxProc.}
  var err: ERR_OPTIONS_NEW
  let opt = options_new(addr err)
  ctoxAssert(TOX_ERR_OPTIONS_NEW_OK, err)
  defer: options_free(opt)
  options_default(opt)
  configure(opt)
  block:
    var err: ERR_NEW
    result = Tox(core: tox_new(opt, addr err))
    ctoxAssert(TOX_ERR_NEW_OK, err)

proc newTox*(): Tox =
  ## Create a new Tox instance.
  var err: ERR_NEW
  result = Tox(core: tox_new(nil, addr err))
  ctoxAssert(TOX_ERR_NEW_OK, err)

proc close*(tox: Tox) {.tags: [IOEffect].} =
  ## Shutdown and destroy a Tox instance.
  proc kill(core: Core) {.ctoxProc.}
  if not tox.core.pointer.isNil:
    tox.core.kill()
    reset tox.core

func isClosed*(tox: Tox): bool = tox.core.pointer.isNil

proc saveData*(tox: Tox): string =
  ## Retrieve save data of `tox` instance.
  ##
  ## .. code-block:: nim
  ##   writeFile("tox.save", tox.savedata)
  ##
  proc get_savedata_size(core: Core): csize {.ctoxProc.}
  proc get_savedata(core: Core; savedata: ptr char) {.ctoxProc.}
  result = newString(tox.core.get_savedata_size())
  if 0 < result.len:
    tox.core.get_savedata(addr result[0])

type
  Err_Bootstrap {.ctoxEnum.} = enum
    TOX_ERR_BOOTSTRAP_OK,
    TOX_ERR_BOOTSTRAP_NULL,
    TOX_ERR_BOOTSTRAP_BAD_HOST,
    TOX_ERR_BOOTSTRAP_BAD_PORT

const
  defaultPort* = 33445'u16

proc bootstrap*(tox: Tox; host: string; key: PublicKey; port = defaultPort) {.
    tags: [IOEffect].} =
  ## Bootstap the `tox` DHT state.
  proc bootstrap(
    core: Core; host: cstring; port: uint16;
    public_key: ptr uint8; error: ptr Err_Bootstrap): bool {.ctoxProc.}
  var err = TOX_ERR_BOOTSTRAP_OK
  discard bootstrap(tox.core, host, port, unsafeAddr key.bytes[0], addr err)
  ctoxAssert(TOX_ERR_BOOTSTRAP_OK, err)

proc addTcpRelay*(tox: Tox; host: string; port: uint16; key: PublicKey) =
  ## Add a TCP relay to `tox`.
  proc add_tcp_relay(
    core: Core; host: cstring; port: uint16;
    public_key: ptr uint8; error: ptr Err_Bootstrap): bool {.ctoxProc.}
  var err = TOX_ERR_BOOTSTRAP_OK
  discard tox.core.add_tcp_relay(host, port, unsafeAddr key.bytes[0], addr err)
  ctoxAssert(TOX_ERR_BOOTSTRAP_OK, err)

template callbackSetter(name, body: untyped) =
  ## Magic for installing Nim closure callbacks into c-toxcore.
  proc `on name`*(tox: Tox; cb: `Cb name`) =
    template callThru(args: varargs[untyped]) =
      let tox = cast[Tox](user_data)
      if not tox.name.isNil: tox.name(args)
    body
    proc name(core: Core; callback: cbType) {.ctoxCallbackProc.}
    tox.name = cb
    if cb.isNil: `name`(tox.core, nil)
    else: `name`(tox.core, wrapper)

callbackSetter self_connection_status:
  ## Install a callback for handling the instance connection state.
  type cbType = proc (
    core: Core; connection_status: Connection; user_data: pointer) {.cdecl.}
  proc wrapper(core: Core; status: Connection; user_data: pointer) {.cdecl.} =
    callThru(status)

proc iteration_interval*(tox: Tox): int =
  ## Return the time in milliseconds before `iterate(tox)` should be called again
  ## for optimal performance.
  proc iteration_interval(core: Core): uint32 {.ctoxProc.}
  (int)tox.core.iteration_interval()

proc iterate*(tox: Tox) {.tags: [IOEffect].} =
  ##  Iterate the Tox main loop.
  ##
  ## .. code-block:: nim
  ##   while true:
  ##     poll(tox.iterationInterval)
  ##     tox.itererate()
  proc iterate(core: Core; user_data: pointer) {.ctoxProc.}
  tox.core.iterate(cast[pointer](tox))

proc address*(tox: Tox): Address =
  ## Retrieve the current address of `tox` that can be used to initiate
  ## friend requests. This includes a public key, a nospam cookie,
  ## and a checksum.
  proc self_get_address(core: Core; address: ptr uint8) {.ctoxProc.}
  tox.core.self_get_address(addr result.bytes[0])

proc `noSpam=`*(tox: Tox; noSpam: NoSpam) =
  ## Set a new nospam cookie. This prevents new friend requests
  ## using the previous nospam from reaching `tox`.
  proc self_set_nospam(core: Core; nospam: NoSpam) {.ctoxProc.}
  tox.core.self_set_nospam(noSpam)

proc noSpam*(tox: Tox): NoSpam =
  ## Retrieve the current nospam cookie of `tox`.
  proc self_get_nospam(core: Core): NoSpam {.ctoxProc.}
  tox.core.self_get_nospam()

proc publicKey*(tox: Tox): PublicKey =
  ## Retrieve the public key of `tox`.
  proc self_get_public_key(core: Core; public_key: ptr uint8) {.ctoxProc.}
  tox.core.self_get_public_key(addr result.bytes[0])

proc secretKey*(tox: Tox): SecretKey =
  ## Retrieve the secret key of `tox`.
  proc self_get_secret_key(core: Core; secret_key: ptr uint8) {.ctoxProc.}
  tox.core.self_get_secret_key(addr result.bytes[0])

type
  Err_Set_Info {.ctoxEnum.} = enum
    TOX_ERR_SET_INFO_OK,
    TOX_ERR_SET_INFO_NULL,
    TOX_ERR_SET_INFO_TOO_LONG

proc `name=`*(tox: Tox; name: string) {.tags: [IOEffect].} =
  ## Set the display name of `tox` instance and propagate it to friends.
  proc self_set_name(
    core: Core; name: cstring; length: csize;
    error: ptr Err_Set_Info): bool {.ctoxProc.}
  var err = TOX_ERR_SET_INFO_OK
  discard tox.core.self_set_name(name, name.len, nil)
  ctoxAssert(TOX_ERR_SET_INFO_OK, err)

proc name*(tox: Tox): string =
  ## Retrieve the display name of `tox` instance.
  proc self_get_name_size(core: Core): csize {.ctoxProc.}
  proc self_get_name(core: Core; name: ptr char) {.ctoxProc.}
  result = newString(tox.core.self_get_name_size())
  if 0 < result.len:
    tox.core.self_get_name(addr result[0])

proc `statusMessage=`*(tox: Tox; msg: string) {.tags: [IOEffect].} =
  ## Set the status message of `tox` instance and propagate it to friends.
  proc self_set_status_message(
    core: Core; status_message: cstring;
    length: csize; error: ptr Err_Set_Info): bool {.ctoxProc.}
  var err = TOX_ERR_SET_INFO_OK
  discard tox.core.self_set_status_message(msg, msg.len, addr err)
  ctoxAssert(TOX_ERR_SET_INFO_OK, err)

proc statusMessage*(tox: Tox): string {.tags: [IOEffect].} =
  ## Retrieve the status message of `tox` instance.
  proc self_get_status_message_size(core: Core): csize {.ctoxProc.}
  proc self_get_status_message(core: Core; status_message: ptr char) {.ctoxProc.}
  result = newString(tox.core.self_get_status_message_size)
  if 0 < result.len:
    tox.core.self_get_status_message(addr result[0])

proc `status=`*(tox: Tox; status: UserStatus) {.tags: [IOEffect].} =
  ## Set the status of `tox` instance.
  proc self_set_status(core: Core; status: UserStatus) {.ctoxProc.}
  tox.core.self_set_status(status)

proc status*(tox: Tox): UserStatus =
  ## Retrieve the status of `tox` instance.
  proc self_get_status(core: Core): UserStatus {.ctoxProc.}
  tox.core.self_get_status()

type Err_Friend_Add {.ctoxEnum.} = enum
  TOX_ERR_FRIEND_ADD_OK,
  TOX_ERR_FRIEND_ADD_NULL,
  TOX_ERR_FRIEND_ADD_TOO_LONG,
  TOX_ERR_FRIEND_ADD_NO_MESSAGE,
  TOX_ERR_FRIEND_ADD_OWN_KEY,
  TOX_ERR_FRIEND_ADD_ALREADY_SENT,
  TOX_ERR_FRIEND_ADD_BAD_CHECKSUM,
  TOX_ERR_FRIEND_ADD_SET_NEW_NOSPAM,
  TOX_ERR_FRIEND_ADD_MALLOC

proc addFriend*(tox: Tox; id: Address; msg: string): Friend {.tags: [IOEffect].} =
  ## Issue a friend request and return a token for the pending friend.
  proc friend_add(
    core: Core; address: ptr uint8; message: cstring;
    length: csize; error: ptr ERR_FRIEND_ADD): Friend {.ctoxProc.}
  var err = TOX_ERR_FRIEND_ADD_OK
  result = tox.core.friend_add(unsafeAddr id.bytes[0], msg, msg.len, addr err)
  ctoxAssert(TOX_ERR_FRIEND_ADD_OK, err)

proc addFriendNoRequest*(tox: Tox; key: PublicKey): Friend {.tags: [IOEffect].} =
  ## Respond to a friend request and return a token for the new friend.
  proc friend_add_norequest(
    core: Core; public_key: ptr uint8;
    error: ptr ERR_FRIEND_ADD): Friend {.ctoxProc.}
  var err = TOX_ERR_FRIEND_ADD_OK
  result = tox.core.friend_add_norequest(
    unsafeAddr key.bytes[0], addr err)
  ctoxAssert(TOX_ERR_FRIEND_ADD_OK, err)

type
  Err_Friend_Delete {.ctoxEnum.} = enum
    TOX_ERR_FRIEND_DELETE_OK,
    TOX_ERR_FRIEND_DELETE_FRIEND_NOT_FOUND

proc delete*(tox: Tox; friend: Friend): bool {.tags: [IOEffect].} =
  ## Revoke a friend.
  proc friend_delete(
    core: Core; friend: Friend;
    error: ptr Err_Friend_Delete): bool {.ctoxProc.}
  var err = TOX_ERR_FRIEND_DELETE_OK
  discard tox.core.friend_delete(friend, addr err)
  ctoxAssert(TOX_ERR_FRIEND_DELETE_OK, err)

type Err_Friend_By_Public_Key {.ctoxEnum.} = enum
  TOX_ERR_FRIEND_BY_PUBLIC_KEY_OK,
  TOX_ERR_FRIEND_BY_PUBLIC_KEY_NULL,
  TOX_ERR_FRIEND_BY_PUBLIC_KEY_NOT_FOUND

proc friend*(tox: Tox; key: PublicKey): Friend =
  ## Retrieve a friend handle by public key.
  proc friend_by_public_key(
    core: Core; public_key: ptr uint8;
    error: ptr Err_Friend_By_Public_Key): Friend {.ctoxProc.}
  var err = TOX_ERR_FRIEND_BY_PUBLIC_KEY_OK
  result = tox.core.friend_by_public_key(unsafeAddr key.bytes[0], addr err)
  ctoxAssert(TOX_ERR_FRIEND_BY_PUBLIC_KEY_OK, err)

proc exists*(tox: Tox; friend: Friend): bool =
  ## Test if a friend exists.
  proc friend_exists(core: Core; friend: Friend): bool {.ctoxProc.}
  tox.core.friend_exists(friend)

proc friends*(tox: Tox): seq[Friend] =
  ## Retrieve handles for all friends.
  proc self_get_friend_list_size(core: Core): csize {.ctoxProc.}
  proc self_get_friend_list(core: Core; friend_list: ptr Friend) {.ctoxProc.}
  result = newSeq[Friend](tox.core.self_get_friend_list_size())
  if 0 < result.len:
    tox.core.self_get_friend_list(addr result[0])

type Err_Friend_Get_Public_Key {.ctoxEnum.} = enum
  TOX_ERR_FRIEND_GET_PUBLIC_KEY_OK,
  TOX_ERR_FRIEND_GET_PUBLIC_KEY_FRIEND_NOT_FOUND

proc publicKey*(tox: Tox; friend: Friend): PublicKey =
  ## Retrieve the public key for a given friend handle.
  proc friend_get_public_key(
    core: Core; friend: Friend;
    public_key: ptr uint8;
    error: ptr Err_Friend_Get_Public_Key): bool {.ctoxProc.}
  var err = TOX_ERR_FRIEND_GET_PUBLIC_KEY_OK
  discard tox.core.friend_get_public_key(friend, addr result.bytes[0], addr err)
  ctoxAssert(TOX_ERR_FRIEND_GET_PUBLIC_KEY_OK, err)

type Err_Friend_Get_Last_Online {.ctoxEnum.} = enum
  TOX_ERR_FRIEND_GET_LAST_ONLINE_OK,
  TOX_ERR_FRIEND_GET_LAST_ONLINE_FRIEND_NOT_FOUND

proc lastOnline*(tox: Tox; friend: Friend): uint64 =
  ## Retrieve the last time a friend was known to be online in Unix epoch time.
  proc friend_get_last_online(
    core: Core; friend: Friend;
    error: ptr Err_Friend_Get_Last_Online): uint64 {.ctoxProc.}
  var err = TOX_ERR_FRIEND_GET_LAST_ONLINE_OK
  result = tox.core.friend_get_last_online(friend, addr err)
  ctoxAssert(TOX_ERR_FRIEND_GET_LAST_ONLINE_OK, err)

type Err_Friend_Query {.ctoxEnum.} = enum
  TOX_ERR_FRIEND_QUERY_OK,
  TOX_ERR_FRIEND_QUERY_NULL,
  TOX_ERR_FRIEND_QUERY_FRIEND_NOT_FOUND

proc name*(tox: Tox; friend: Friend): string =
  ## Retrieve the name of a friend by handle.
  proc friend_get_name_size(
    core: Core; friend: Friend;
    error: ptr Err_Friend_Query): csize {.ctoxProc.}
  proc friend_get_name(
    core: Core; friend: Friend; name: ptr char;
    error: ptr Err_Friend_Query): bool {.ctoxProc.}
  var err = TOX_ERR_FRIEND_QUERY_OK
  result = newString(tox.core.friend_get_name_size(friend, addr err))
  ctoxAssert(TOX_ERR_FRIEND_QUERY_OK, err)
  if 0 < result.len:
    discard tox.core.friend_get_name(friend, addr result[0], addr err)
    ctoxAssert(TOX_ERR_FRIEND_QUERY_OK, err)

callbackSetter friend_name:
  ## Install a callback for friend name updates.
  type cbType = proc (
    core: Core; friend: Friend; name: ptr uint8;
    length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend; name: ptr uint8;
      length: csize; user_data: pointer) {.cdecl.} =
    callThru(friend, ctoxString(name, length))

proc statusMessage*(tox: Tox; friend: Friend): string =
  ## Retrieve the status message of a friend.
  proc friend_get_status_message_size(
    core: Core; friend: Friend;
    error: ptr Err_Friend_Query): csize {.ctoxProc.}
  proc friend_get_status_message(
    core: Core; friend: Friend;
    status_message: ptr char;
    error: ptr Err_Friend_Query): bool {.ctoxProc.}
  var err = TOX_ERR_FRIEND_QUERY_OK
  result = newString(tox.core.friend_get_status_message_size(friend, addr err))
  ctoxAssert(TOX_ERR_FRIEND_QUERY_OK, err)
  if 0 < result.len:
    discard tox.core.friend_get_status_message(friend, addr result[0], addr err)
    ctoxAssert(TOX_ERR_FRIEND_QUERY_OK, err)

callbackSetter friend_status_message:
  ## Install a callback for friend status messages.
  type cbType = proc (
    core: Core; friend: Friend;
    message: ptr uint8; length: csize;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      message: ptr uint8; length: csize;
      user_data: pointer) {.cdecl.} =
    callThru(friend, ctoxString(message, length))

proc status*(tox: Tox; friend: Friend): UserStatus =
  ## Retrieve the status of a friend.
  proc friend_get_status(
    core: Core; friend: Friend;
    error: ptr Err_Friend_Query): UserStatus {.ctoxProc.}
  var err: Err_Friend_Query
  result = tox.core.friend_get_status(friend, addr err)
  ctoxAssert(TOX_ERR_FRIEND_QUERY_OK, err)

callbackSetter friend_status:
  ## Install a callback for friend statuses.
  type cbType = proc (
    core: Core; friend: Friend;
    status: UserStatus; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      status: UserStatus; user_data: pointer) {.cdecl.} =
    callThru(friend, status)

proc connectionStatus*(tox: Tox; friend: Friend): Connection =
  ## Retrieve the connection status of a friend.
  proc friend_get_connection_status(
    core: Core; friend: Friend;
    error: ptr Err_Friend_Query): Connection {.ctoxProc.}
  var err = TOX_ERR_FRIEND_QUERY_OK
  result = tox.core.friend_get_connection_status(friend, addr err)
  ctoxAssert(TOX_ERR_FRIEND_QUERY_OK, err)

callbackSetter friend_connection_status:
  ## Install a callback for friend connection statuses.
  type cbType = proc (
    core: Core; friend: Friend;
    connection_status: Connection;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      status: Connection;
      user_data: pointer) {.cdecl.} =
    callThru(friend, status)

proc typing*(tox: Tox; friend: Friend): bool =
  ## Retrieve the typing status of a friend.
  proc friend_get_typing(
    core: Core; friend: Friend;
    error: ptr Err_Friend_Query): bool {.ctoxProc.}
  var err = TOX_ERR_FRIEND_QUERY_OK
  result = tox.core.friend_get_typing(friend, addr err)
  ctoxAssert(TOX_ERR_FRIEND_QUERY_OK, err)

callbackSetter friend_typing:
  ## Install a callback for friend typing statuses.
  type cbType = proc (
    core: Core; friend: Friend; is_typing: bool;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend; is_typing: bool;
      user_data: pointer) {.cdecl.} =
    let tox = cast[Tox](user_data)
    if not tox.friendTyping.isNil:
      tox.friendTyping(friend, is_typing)

type
  Err_Set_Typing* {.ctoxEnum.} = enum
    TOX_ERR_SET_TYPING_OK,
    TOX_ERR_SET_TYPING_FRIEND_NOT_FOUND

proc typing*(tox: Tox; friend: Friend; typing: bool) {.tags: [IOEffect].} =
  ## Set the typing status of `tox` instance.
  proc self_set_typing(
    core: Core; friend: Friend; typing: bool;
    error: ptr Err_Set_Typing): bool {.ctoxProc.}
  var err = TOX_ERR_SET_TYPING_OK
  discard tox.core.self_set_typing(friend, typing, addr err)
  ctoxAssert(TOX_ERR_SET_TYPING_OK, err)

type Err_Friend_Send_Message {.ctoxEnum.} = enum
  TOX_ERR_FRIEND_SEND_MESSAGE_OK,
  TOX_ERR_FRIEND_SEND_MESSAGE_NULL,
  TOX_ERR_FRIEND_SEND_MESSAGE_FRIEND_NOT_FOUND,
  TOX_ERR_FRIEND_SEND_MESSAGE_FRIEND_NOT_CONNECTED,
  TOX_ERR_FRIEND_SEND_MESSAGE_SENDQ,
  TOX_ERR_FRIEND_SEND_MESSAGE_TOO_LONG,
  TOX_ERR_FRIEND_SEND_MESSAGE_EMPTY

proc send*(tox: Tox; friend: Friend; msg: string;
    kind = TOX_MESSAGE_TYPE_NORMAL): MessageId {.tags: [IOEffect].} =
  ## Send a message to a friend.
  proc friend_send_message(
    core: Core; friend: Friend;
    kind: MessageType; message: cstring;
    length: csize; error: ptr ERR_FRIEND_SEND_MESSAGE): MessageId {.ctoxProc.}
  var err = TOX_ERR_FRIEND_SEND_MESSAGE_OK
  result = tox.core.friend_send_message(friend, kind, msg, msg.len, addr err)
  ctoxAssert(TOX_ERR_FRIEND_SEND_MESSAGE_OK, err)

callbackSetter friend_read_receipt:
  ## Install a callback for message read receipts.
  type cbType = proc (
    core: Core; friend: Friend;
    message_id: MessageId; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      message_id: MessageId; user_data: pointer) {.cdecl.} =
    let tox = cast[Tox](user_data)
    if not tox.friendReadReceipt.isNil:
      tox.friendReadReceipt(friend, message_id)

callbackSetter friend_request:
  ## Install a callback for friend requests.
  type cbType = proc (
    core: Core; public_key: ptr uint8;
    message: ptr uint8; length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; public_key: ptr uint8;
      message: ptr uint8; length: csize;
      user_data: pointer) {.cdecl.} =
    callThru(ctoxArray[PublicKey](public_key), ctoxString(message, length))

callbackSetter friend_message:
  ## Install a callback for friend messages.
  type cbType = proc (
    core: Core; friend: Friend;
    kind: MessageType; message: ptr uint8;
    length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      kind: MessageType; message: ptr uint8;
      length: csize; user_data: pointer) {.cdecl.} =
    callThru(friend, ctoxString(message, length), kind)

proc hash(hash: ptr uint8; data: pointer; length: csize): bool {.ctoxProc.}

proc hash*(data: pointer; size: int): Hash =
  ## Generate cryptographic hash of the given data,
  ## provided primarily for validating cached avatars.
  discard hash(addr result.bytes[0], data, size)

proc hash*(data: string): Hash =
  ## Generate cryptographic hash of the given data.
  discard hash(addr result.bytes[0], unsafeAddr data[0], data.len)

type Err_File_Control {.ctoxEnum.} = enum
  TOX_ERR_FILE_CONTROL_OK,
  TOX_ERR_FILE_CONTROL_FRIEND_NOT_FOUND,
  TOX_ERR_FILE_CONTROL_FRIEND_NOT_CONNECTED,
  TOX_ERR_FILE_CONTROL_NOT_FOUND,
  TOX_ERR_FILE_CONTROL_NOT_PAUSED,
  TOX_ERR_FILE_CONTROL_DENIED,
  TOX_ERR_FILE_CONTROL_ALREADY_PAUSED,
  TOX_ERR_FILE_CONTROL_SENDQ

proc control*(tox: Tox; friend: Friend; file: FileTransfer;
    control: FileControl) {.tags: [IOEffect].} =
  proc file_control(
    core: Core; friend: Friend; file: FileTransfer;
    control: FileControl;
    error: ptr ERR_FILE_CONTROL): bool {.ctoxProc.}
  var err: Err_File_Control
  discard tox.core.file_control(friend, file, control, addr err)
  ctoxAssert(TOX_ERR_FILE_CONTROL_OK, err)

callbackSetter file_recv_control:
  type cbType = proc (
    core: Core; friend: Friend;
    file: FileTransfer; control: FileControl;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      file: FileTransfer; control: FileControl;
      user_data: pointer) {.cdecl.} =
    callThru(friend, file, control)

type Err_File_Seek {.ctoxEnum.} = enum
  TOX_ERR_FILE_SEEK_OK,
  TOX_ERR_FILE_SEEK_FRIEND_NOT_FOUND,
  TOX_ERR_FILE_SEEK_FRIEND_NOT_CONNECTED,
  TOX_ERR_FILE_SEEK_NOT_FOUND,
  TOX_ERR_FILE_SEEK_DENIED,
  TOX_ERR_FILE_SEEK_INVALID_POSITION,
  TOX_ERR_FILE_SEEK_SENDQ

proc seek*(tox: Tox; friend: Friend; file: FileTransfer; pos: uint64) {.tags: [IOEffect].} =
  proc file_seek(
    core: Core; friend: Friend; file: FileTransfer;
    position: uint64; error: ptr Err_File_Seek): bool {.ctoxProc.}
  var err: Err_File_Seek
  discard tox.core.file_seek(friend, file, pos, addr err)
  ctoxAssert(TOX_ERR_FILE_SEEK_OK, err)

type Err_File_Get {.ctoxEnum.} = enum
  TOX_ERR_FILE_GET_OK,
  TOX_ERR_FILE_GET_NULL,
  TOX_ERR_FILE_GET_FRIEND_NOT_FOUND,
  TOX_ERR_FILE_GET_NOT_FOUND

type FileId = array[TOX_FILE_ID_LENGTH, uint8]

proc id*(tox: Tox; friend: Friend; file: FileTransfer): FileId =
  proc file_get_file_id(
    core: Core; friend: Friend;
    file: FileTransfer; file_id: ptr uint8;
    error: ptr Err_File_Get): bool {.ctoxProc.}
  var err: Err_File_Get
  discard tox.core.file_get_file_id(friend, file, addr result[0], addr err)
  ctoxAssert(TOX_ERR_FILE_GET_OK, err)

type Err_File_Send {.ctoxEnum.} = enum
  TOX_ERR_FILE_SEND_OK,
  TOX_ERR_FILE_SEND_NULL,
  TOX_ERR_FILE_SEND_FRIEND_NOT_FOUND,
  TOX_ERR_FILE_SEND_FRIEND_NOT_CONNECTED,
  TOX_ERR_FILE_SEND_NAME_TOO_LONG,
  TOX_ERR_FILE_SEND_TOO_MANY

proc send*(tox: Tox; friend: Friend; kind: uint32; size: BiggestInt; id : Hash;
    filename: string): FileTransfer {.tags: [IOEffect].} =
  proc file_send(
    core: Core; friend: Friend; kind: uint32;
    file_size: uint64; file_id: ptr uint8; filename: cstring;
    filename_length: csize; error: ptr Err_File_Send): FileTransfer {.ctoxProc.}
  var err: Err_File_Send
  result = tox.core.file_send(
    friend, kind, size.uint64, unsafeAddr id.bytes[0], filename, filename.len, addr err)
  ctoxAssert(TOX_ERR_FILE_SEND_OK, err)

proc send*(tox: Tox; friend: Friend; kind: uint32; size: BiggestInt;
    filename: string): FileTransfer {.tags: [IOEffect].} =
  proc file_send(
    core: Core; friend: Friend; kind: uint32;
    file_size: uint64; file_id: ptr uint8; filename: cstring;
    filename_length: csize; error: ptr Err_File_Send): FileTransfer {.ctoxProc.}
  var err: Err_File_Send
  result = tox.core.file_send(
    friend, kind, size.uint64, nil, filename, filename.len, addr err)
  ctoxAssert(TOX_ERR_FILE_SEND_OK, err)

type Err_File_Send_Chunk {.ctoxEnum.} = enum
  TOX_ERR_FILE_SEND_CHUNK_OK,
  TOX_ERR_FILE_SEND_CHUNK_NULL,
  TOX_ERR_FILE_SEND_CHUNK_FRIEND_NOT_FOUND,
  TOX_ERR_FILE_SEND_CHUNK_FRIEND_NOT_CONNECTED,
  TOX_ERR_FILE_SEND_CHUNK_NOT_FOUND,
  TOX_ERR_FILE_SEND_CHUNK_NOT_TRANSFERRING,
  TOX_ERR_FILE_SEND_CHUNK_INVALID_LENGTH,
  TOX_ERR_FILE_SEND_CHUNK_SENDQ,
  TOX_ERR_FILE_SEND_CHUNK_WRONG_POSITION

proc sendChunk*(tox: Tox; friend: Friend; file: FileTransfer; pos: uint64;
    data: pointer; size: int) {.tags: [IOEffect].} =
  proc file_send_chunk(
    core: Core; friend: Friend;
    file: FileTransfer; position: uint64;
    data: pointer; length: csize;
    error: ptr Err_File_Send_Chunk): bool {.ctoxProc.}
  var err: Err_File_Send_Chunk
  discard tox.core.file_send_chunk(friend, file, pos, data, size, addr err)
  ctoxAssert(TOX_ERR_FILE_SEND_CHUNK_OK, err)

proc sendChunk*(tox: Tox; friend: Friend; file: FileTransfer; pos: uint64;
    data: string) =
  if data.len == 0:
    sendChunk(tox, friend, file, pos, nil, 0)
  else:
    sendChunk(tox, friend, file, pos, data[0].unsafeAddr, data.len)

callbackSetter file_chunk_request:
  type cbType = proc (
    core: Core; friend: Friend;
    file: FileTransfer; position: uint64;
    length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      file: FileTransfer; position: uint64;
      length: csize; user_data: pointer) {.cdecl.} =
    callThru(friend, file, position, length)

callbackSetter file_recv:
  type cbType = proc (
    core: Core; friend: Friend;
    file: FileTransfer; kind: uint32; file_size: uint64;
    filename: ptr uint8; filename_length: csize;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      file: FileTransfer; kind: uint32; file_size: uint64;
      filename: ptr uint8; filename_length: csize;
      user_data: pointer) {.cdecl.} =
    callThru(friend, file, kind, fileSize, ctoxString(filename, filenameLength))

callbackSetter file_recv_chunk:
  type cbType = proc (
    core: Core; friend: Friend;
    file: FileTransfer; position: uint64;
    data: ptr uint8; length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      file: FileTransfer; position: uint64;
      data: ptr uint8; length: csize; user_data: pointer) {.cdecl.} =
    callThru(friend, file, position, data, length)

callbackSetter conference_invite:
  type cbType = proc (
    core: Core; friend: Friend;
    kind: ConferenceType; cookie: ptr uint8;
    length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      kind: ConferenceType; cookie: ptr uint8;
      length: csize; user_data: pointer) {.cdecl.} =
    callThru(friend, kind, ctoxString(cookie, length))

callbackSetter conference_connected:
  type cbType = proc (
    core: Core; conf: Conference;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; conf: Conference;
      user_data: pointer) {.cdecl.} =
    callThru(conf)

callbackSetter conference_message:
  type cbType = proc (
    core: Core; conf: Conference;
    peer: Peer; kind: MessageType;
    message: ptr uint8; length: csize;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; conf: Conference;
      peer: Peer; kind: MessageType;
      message: ptr uint8; length: csize;
      user_data: pointer) {.cdecl.} =
    callThru(conf, peer, kind, ctoxString(message, length))

callbackSetter conference_title:
  type cbType = proc (
    core: Core; conf: Conference;
    peer: Peer; title: ptr uint8;
    length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; conf: Conference;
      peer: Peer; title: ptr uint8;
      length: csize; user_data: pointer) {.cdecl.} =
    callThru(conf, peer, ctoxString(title, length))

callbackSetter conference_peer_name:
  type cbType = proc (
    core: Core; conf: Conference;
    peer: Peer; name: ptr uint8;
    length: csize; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; conf: Conference;
      peer: Peer; name: ptr uint8;
      length: csize; user_data: pointer) {.cdecl.} =
    callThru(conf, peer, ctoxString(name, length))

callbackSetter conference_peer_list_changed:
  type cbType = proc (
    core: Core; conf: Conference; user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; conf: Conference; user_data: pointer) {.cdecl.} =
    callThru(conf)

type Err_Conference_New {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_NEW_OK,
  TOX_ERR_CONFERENCE_NEW_INIT

proc newConference*(tox: Tox): Conference {.tags: [IOEffect].} =
  proc conference_new(
    core: Core; error: ptr Err_Conference_New): Conference {.ctoxProc.}
  var err: Err_Conference_New
  result = tox.core.conference_new(addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_NEW_OK, err)

type Err_Conference_Delete {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_DELETE_OK,
  TOX_ERR_CONFERENCE_DELETE_CONFERENCE_NOT_FOUND

proc delete*(tox: Tox; conf: Conference) {.tags: [IOEffect].} =
  proc tox_conference_delete(
    core: Core; conference: Conference;
    error: ptr Err_Conference_Delete): bool {.ctoxProc.}
  var err: Err_Conference_Delete
  discard tox.core.tox_conference_delete(conf, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_DELETE_OK, err)

type
  Err_Conference_Peer_Query {.ctoxEnum.} = enum
    TOX_ERR_CONFERENCE_PEER_QUERY_OK,
    TOX_ERR_CONFERENCE_PEER_QUERY_CONFERENCE_NOT_FOUND,
    TOX_ERR_CONFERENCE_PEER_QUERY_PEER_NOT_FOUND,
    TOX_ERR_CONFERENCE_PEER_QUERY_NO_CONNECTION

proc peerCount*(tox: Tox; conf: Conference): uint32 =
  proc conference_peer_count(
    core: Core; conf: Conference;
    error: ptr Err_Conference_Peer_Query): uint32 {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  result = tox.core.conference_peer_count(conf, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

proc peerName*(tox: Tox; conf: Conference; peer: Peer): string =
  proc conference_peer_get_name_size(
    core: Core; conf: Conference; peer: Peer;
    error: ptr Err_Conference_Peer_Query): csize {.ctoxProc.}
  proc conference_peer_get_name(
    core: Core; conf: Conference; peer: Peer; name: ptr char;
    error: ptr Err_Conference_Peer_Query): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  result = newString(tox.core.conference_peer_get_name_size(conf, peer, addr err))
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)
  if 0 < result.len:
    discard tox.core.conference_peer_get_name(conf, peer, addr result[0], addr err)
    ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

proc peerPublicKey*(tox: Tox; conf: Conference; peer: Peer): PublicKey =
  proc conference_peer_get_public_key(
    core: Core; conf: Conference; peer: Peer; public_key: ptr uint8;
    error: ptr Err_Conference_Peer_Query): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  discard tox.core.conference_peer_get_public_key(conf, peer, addr result.bytes[
      0], addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

proc peerNumberIsOurs*(tox: Tox; conf: Conference; peer: Peer): bool =
  proc conference_peer_number_is_ours(
    core: Core; conf: Conference; peer: Peer;
    error: ptr Err_Conference_Peer_Query): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  result = tox.core.conference_peer_number_is_ours(conf, peer, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

proc offlinePeerCount*(tox: Tox; conf: Conference): uint32 =
  proc conference_offline_peer_count(
    core: Core; conf: Conference;
    error: ptr Err_Conference_Peer_Query): uint32 {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  result = tox.core.conference_offline_peer_count(conf, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

proc offlinePeerName*(tox: Tox; conf: Conference; peer: Peer): string =
  proc conference_offline_peer_get_name_size(
    core: Core; conf: Conference; offline_peer: Peer;
    error: ptr Err_Conference_Peer_Query): csize {.ctoxProc.}
  proc conference_offline_peer_get_name(core: Core;
      conf: Conference; offline_peer: Peer; name: ptr char;
      error: ptr Err_Conference_Peer_Query): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  result = newString(tox.core.conference_offline_peer_get_name_size(conf, peer, addr err))
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)
  if 0 < result.len:
    discard tox.core.conference_offline_peer_get_name(conf, peer, addr result[
        0], addr err)
    ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

proc offlinePeerPublicKey*(tox: Tox; conf: Conference; peer: Peer): PublicKey =
  proc conference_offline_peer_get_public_key(
    core: Core; conf: Conference; offline_peer: Peer; public_key: ptr uint8;
    error: ptr Err_Conference_Peer_Query): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  discard tox.core.conference_offline_peer_get_public_key(
    conf, peer, addr result.bytes[0], addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

proc offflinePeerLastActive*(tox: Tox; conf: Conference; peer: Peer): uint64 =
  proc conference_offline_peer_get_last_active(
    core: Core; conf: Conference; offline_peer: Peer;
    error: ptr Err_Conference_Peer_Query): uint64 {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_PEER_QUERY_OK
  result = tox.core.conference_offline_peer_get_last_active(conf, peer, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_PEER_QUERY_OK, err)

type Err_Conference_Set_Max_Offline {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_SET_MAX_OFFLINE_OK,
  TOX_ERR_CONFERENCE_SET_MAX_OFFLINE_CONFERENCE_NOT_FOUND

proc `maxOffline=`*(tox: Tox; conf: Conference; peers: uint32) =
  proc conference_set_max_offline(
    core: Core; conf: Conference;
    max_offline_peers: uint32;
    error: ptr Err_Conference_Set_Max_Offline): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_SET_MAX_OFFLINE_OK
  discard tox.core.conference_set_max_offline(conf, peers, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_SET_MAX_OFFLINE_OK, err)

type Err_Conference_Invite {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_INVITE_OK,
  TOX_ERR_CONFERENCE_INVITE_CONFERENCE_NOT_FOUND,
  TOX_ERR_CONFERENCE_INVITE_FAIL_SEND,
  TOX_ERR_CONFERENCE_INVITE_NO_CONNECTION

proc invite*(tox: Tox; friend: Friend; conf: Conference) {.tags: [IOEffect].} =
  proc conference_invite(
    core: Core; friend: Friend;
    conference: Conference;
    error: ptr Err_Conference_Invite): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_INVITE_OK
  discard tox.core.conference_invite(friend, conf, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_INVITE_OK, err)

type Err_Conference_Join {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_JOIN_OK,
  TOX_ERR_CONFERENCE_JOIN_INVALID_LENGTH,
  TOX_ERR_CONFERENCE_JOIN_WRONG_TYPE,
  TOX_ERR_CONFERENCE_JOIN_FRIEND_NOT_FOUND,
  TOX_ERR_CONFERENCE_JOIN_DUPLICATE,
  TOX_ERR_CONFERENCE_JOIN_INIT_FAIL,
  TOX_ERR_CONFERENCE_JOIN_FAIL_SEND

proc join*(tox: Tox; friend: Friend; cookie: string): Conference {.tags: [IOEffect].} =
  proc conference_join(
    core: Core; friend: Friend; cookie: cstring;
    length: csize; error: ptr Err_Conference_Join): Conference {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_JOIN_OK
  result = tox.core.conference_join(friend, cookie, cookie.len, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_JOIN_OK, err)

type Err_Conference_Send_Message {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_SEND_MESSAGE_OK,
  TOX_ERR_CONFERENCE_SEND_MESSAGE_CONFERENCE_NOT_FOUND,
  TOX_ERR_CONFERENCE_SEND_MESSAGE_TOO_LONG,
  TOX_ERR_CONFERENCE_SEND_MESSAGE_NO_CONNECTION,
  TOX_ERR_CONFERENCE_SEND_MESSAGE_FAIL_SEND

proc send*(tox: Tox; conf: Conference; msg: string; kind = TOX_MESSAGE_TYPE_NORMAL): bool {.
    tags: [IOEffect].} =
  proc conference_send_message(
    core: Core; conf: Conference;
    kind: MessageType; message: cstring;
    length: csize;
    error: ptr Err_Conference_Send_Message): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_SEND_MESSAGE_OK
  result = tox.core.conference_send_message(
    conf, kind, msg, msg.len, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_SEND_MESSAGE_OK, err)

type Err_Conference_Title {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_TITLE_OK,
  TOX_ERR_CONFERENCE_TITLE_CONFERENCE_NOT_FOUND,
  TOX_ERR_CONFERENCE_TITLE_INVALID_LENGTH,
  TOX_ERR_CONFERENCE_TITLE_FAIL_SEND

proc title*(tox: Tox; conf: Conference): string =
  proc conference_get_title_size(
    core: Core; conf: Conference;
    error: ptr Err_Conference_Title): csize {.ctoxProc.}
  proc conference_get_title(
    core: Core; conf: Conference; title: ptr char;
    error: ptr Err_Conference_Title): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_TITLE_OK
  result = newString(tox.core.conference_get_title_size(conf, addr err))
  ctoxAssert(TOX_ERR_CONFERENCE_TITLE_OK, err)
  if 0 < result.len:
    discard tox.core.conference_get_title(conf, addr result[0], addr err)
    ctoxAssert(TOX_ERR_CONFERENCE_TITLE_OK, err)

proc `title=`*(tox: Tox; conf: Conference; s: string) {.tags: [IOEffect].} =
  proc conference_set_title(
    core: Core; conf: Conference;
    title: cstring; length: csize;
    error: ptr Err_Conference_Title): bool {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_TITLE_OK
  discard tox.core.conference_set_title(conf, s, s.len, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_TITLE_OK, err)

proc conferences*(tox: Tox): seq[Conference] =
  proc conference_get_chatlist_size(core: Core): csize {.ctoxProc.}
  proc conference_get_chatlist(core: Core; chatlist: ptr Conference) {.ctoxProc.}
  result = newSeq[Conference](tox.core.conference_get_chatlist_size())
  if 0 < result.len:
    tox.core.conference_get_chatlist(addr result[0])

type Err_Conference_Get_Type {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_GET_TYPE_OK,
  TOX_ERR_CONFERENCE_GET_TYPE_CONFERENCE_NOT_FOUND

proc kind*(tox: Tox; conf: Conference): ConferenceType =
  proc conference_get_type(
    core: Core; conf: Conference;
    error: ptr Err_Conference_Get_Type): ConferenceType {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_GET_TYPE_OK
  result = tox.core.conference_get_type(conf, addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_GET_TYPE_OK, err)

proc id*(tox: Tox; conf: Conference): ConferenceId =
  proc conference_get_id(core: Core; conf: Conference; id: ptr uint8): bool {.ctoxProc.}
  ctoxAssert(true, tox.core.conference_get_id(conf, addr result.bytes[0]))

type Err_Conference_By_Id {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_BY_ID_OK,
  TOX_ERR_CONFERENCE_BY_ID_NULL,
  TOX_ERR_CONFERENCE_BY_ID_NOT_FOUND

proc conference*(tox: Tox; id: ConferenceId): Conference =
  proc conference_by_id(
    core: Core; id: ptr uint8;
    error: ptr ERR_CONFERENCE_BY_ID): Conference {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_BY_ID_OK
  result = tox.core.conference_by_id(unsafeAddr id.bytes[0], addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_BY_ID_OK, err)

proc uid*(tox: Tox; conf: Conference): ConferenceUid =
  proc conference_get_uid(
    core: Core; conf: Conference; uid: ptr uint8): bool {.ctoxProc.}
  ctoxAssert(true, tox.core.conference_get_uid(conf, addr result.bytes[0]))

type Err_Conference_By_Uid {.ctoxEnum.} = enum
  TOX_ERR_CONFERENCE_BY_UID_OK,
  TOX_ERR_CONFERENCE_BY_UID_NULL,
  TOX_ERR_CONFERENCE_BY_UID_NOT_FOUND

proc conference*(tox: Tox; uid: ConferenceUid): Conference =
  proc conference_by_uid(
    core: Core; uid: ptr uint8;
    error: ptr Err_Conference_By_Uid): Conference {.ctoxProc.}
  var err = TOX_ERR_CONFERENCE_BY_UID_OK
  result = tox.core.conference_by_uid(unsafeAddr uid.bytes[0], addr err)
  ctoxAssert(TOX_ERR_CONFERENCE_BY_UID_OK, err)

type Err_Friend_Custom_Packet {.ctoxEnum.} = enum
  TOX_ERR_FRIEND_CUSTOM_PACKET_OK,
  TOX_ERR_FRIEND_CUSTOM_PACKET_NULL,
  TOX_ERR_FRIEND_CUSTOM_PACKET_FRIEND_NOT_FOUND,
  TOX_ERR_FRIEND_CUSTOM_PACKET_FRIEND_NOT_CONNECTED,
  TOX_ERR_FRIEND_CUSTOM_PACKET_INVALID,
  TOX_ERR_FRIEND_CUSTOM_PACKET_EMPTY,
  TOX_ERR_FRIEND_CUSTOM_PACKET_TOO_LONG,
  TOX_ERR_FRIEND_CUSTOM_PACKET_SENDQ

proc sendLossyPacket*(tox: Tox; friend: Friend; data: pointer; size: int) {.
    tags: [IOEffect].} =
  proc friend_send_lossy_packet(
    core: Core; friend: Friend;
    data: pointer; length: csize;
    error: ptr Err_Friend_Custom_Packet): bool {.ctoxProc.}
  var err = TOX_ERR_FRIEND_CUSTOM_PACKET_OK
  discard tox.core.friend_send_lossy_packet(friend, data, size, addr err)
  ctoxAssert(TOX_ERR_FRIEND_CUSTOM_PACKET_OK, err)

proc sendLosslessPacket*(tox: Tox; friend: Friend; data: pointer; size: int) {.
    tags: [IOEffect].} =
  proc friend_send_lossless_packet(
    core: Core; friend: Friend;
    data: pointer; length: csize;
    error: ptr Err_Friend_Custom_Packet): bool {.ctoxProc.}
  var err = TOX_ERR_FRIEND_CUSTOM_PACKET_OK
  discard tox.core.friend_send_lossless_packet(friend, data, size, addr err)
  ctoxAssert(TOX_ERR_FRIEND_CUSTOM_PACKET_OK, err)

callbackSetter friend_lossy_packet:
  type cbType = proc (
    core: Core; friend: Friend;
    data: ptr uint8; length: csize;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      data: ptr uint8; length: csize;
      user_data: pointer) {.cdecl.} =
    callThru(friend, data, length)

callbackSetter friend_lossless_packet:
  type cbType = proc (
    core: Core; friend: Friend;
    data: ptr uint8; length: csize;
    user_data: pointer) {.cdecl.}
  proc wrapper(
      core: Core; friend: Friend;
      data: ptr uint8; length: csize;
      user_data: pointer) {.cdecl.} =
    callThru(friend, data, length)

proc dhtId*(tox: Tox): PublicKey =
  proc self_get_dht_id(core: Core; dht_id: ptr uint8) {.ctoxProc.}
  tox.core.self_get_dht_id(addr result.bytes[0])

type Err_Get_Port {.ctoxEnum.} = enum
  TOX_ERR_GET_PORT_OK,
  TOX_ERR_GET_PORT_NOT_BOUND

proc udpPort*(tox: Tox): uint16 =
  proc self_get_udp_port(
    core: Core; error: ptr Err_Get_Port): uint16 {.ctoxProc.}
  var err = TOX_ERR_GET_PORT_OK
  result = tox.core.self_get_udp_port(addr err)
  ctoxAssert(TOX_ERR_GET_PORT_OK, err)

proc tcpPort*(tox: Tox): uint16 =
  proc self_get_tcp_port(
    core: Core; error: ptr Err_Get_Port): uint16 {.ctoxProc.}
  var err = TOX_ERR_GET_PORT_OK
  result = tox.core.self_get_tcp_port(addr err)
  ctoxAssert(TOX_ERR_GET_PORT_OK, err)