summaryrefslogtreecommitdiff
path: root/plugins/Chess4Net/MI/ConnectorUnit.pas
blob: 525ebb3b222d6fc4a52fe1a340f43a3329c87691 (plain)
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
////////////////////////////////////////////////////////////////////////////////
// All code below is exclusively owned by author of Chess4Net - Pavel Perminov
// (packpaul@mail.ru, packpaul1@gmail.com).
// Any changes, modifications, borrowing and adaptation are a subject for
// explicit permition from the owner.

unit ConnectorUnit;

interface

uses
  Classes, ExtCtrls,
  m_globaldefs;

type
  TConnectorEvent = (ceConnected, ceDisconnected, ceData, ceError);

  TConnectorHandler = procedure(ce: TConnectorEvent; d1: pointer = nil;
                                d2: pointer = nil) of object;

  IConnectorable = interface
    procedure ConnectorHandler(ce: TConnectorEvent; d1: pointer = nil; d2: pointer = nil);
  end;

  TConnector = class
  private
    _sendTimer, _sendSystemTimer: TTimer;

    _connected, _opened: boolean;
    _plugin: IConnectorable;
    _hContact, _hFilterMsg: THandle;
    _lstId, _contactLstId: integer;
    // îòñûëàåìîå ñîîáùåíèå
    _msg_sending, _unformated_msg_sending: string;
    _cntrMsgIn: integer;  // ñ÷¸ò÷èê âõîäÿùèõ ñîîáùåíèé
    _cntrMsgOut: integer; // ñ÷¸ò÷èê èñõîäÿùèõ ñîîáùåíèé
    m_iLastCntrMsgOutInFormatting: integer;
    _msg_buf: string; // áóôåð ñîîáùåíèé
    // ñèñòåìíîå ñîîáùåíèå
    _systemDataList: TStringList;
    m_lwId: Longword;
    m_LastSendTime: TDateTime;

{$IFDEF DEBUG_LOG}
    _logFile: Text;

    procedure InitLog;
    procedure WriteToLog(const s: string);
    procedure CloseLog;
{$ENDIF}

    procedure FsendTimerTimer(Sender: TObject);
    procedure FsendSystemTimerTimer(Sender: TObject);

    function FGetOwnerNick: string;
    function FGetContactNick: string;
    function FFilterMsg(msg: string): boolean;
    function FSendMessage(const vMessage: string): boolean;
//    function FNotifySender(const vMessage: string): boolean;
    procedure FNotifySender;
    procedure FSendSystemData(sd: string);
    function FDeformatMsg(var msg: string; out lstId, msgCntr: integer): boolean;
    // Formatting of outgoing messages
    function FFormatMsg(const msg: string): string;
    function FGetOwnerID: integer;
    function FGetMultiSession: boolean;
    procedure FSetMultiSession(bValue: boolean);
    procedure FPluginConnectorHandler(ce: TConnectorEvent;
      d1: pointer = nil; d2: pointer = nil);

  public
    constructor Create(hContact: THandle); reintroduce;
    destructor Destroy; override;

    procedure Close;
    function Open(bMultiSession: boolean = TRUE): boolean;
    function SendData(const d: string): boolean;
    procedure SetPlugin(plugin: IConnectorable);

    property Connected: boolean read _connected;
    property Opened: boolean read _opened;
    property OwnerID: integer read FGetOwnerID;
    property OwnerNick: string read FGetOwnerNick;
    property ContactID: integer read _hContact;
    property ContactNick: string read FGetContactNick;
    property MultiSession: boolean read FGetMultiSession write FSetMultiSession;
  end;

procedure InitConnectorGlobals(const invitationStr, promtHeadStr, dataSeparator: string; maxMsgSize: integer = 256);

implementation

{$J+} {$I-}

uses
  SysUtils, DateUtils, StrUtils, Types,
  m_api,
  ControlUnit;

type
  TConnectorList = class(TList)
  private
    _iterator: integer;
    _hContact: THandle;

    function FGetLastAddedConnector: TConnector;

  public
    procedure AddConnector(Connector: TConnector);
    procedure RemoveConnector(Connector: TConnector);
    function GetFirstConnector(hContact: THandle): TConnector;
    function GetNextConnector: TConnector;
    property LastAddedConnector: TConnector read FGetLastAddedConnector;
  end;

var
  g_connectorList: TConnectorList = nil;
  g_msgBufferSize: integer;
  g_bMultiSession: boolean;

  g_hNotifySender: THandle;

  // cntrMsgIn è cntrMsgOut áûëè ââåäåíû äëÿ ïðåîäîëåíèÿ áàãà ñ çàâèñàþùèìè ñîîáùåíèÿìè

const
  MSG_INVITATION: string = '!&This is a plugin invitation message&!';
  // MSG_RESPOND: string = '!&This is a plugin respond message&!';
  // <ñîîáùåíèå> ::= PROMPT_HEAD [PROMPT_SEPARATOR <èä êëèåíòà>] PROMPT_SEPARATOR <íîìåð ñîîáùåíèÿ> PROMPT_TAIL <ñîîáùåíèå>
  PROMPT_HEAD: string = 'Plgn';
  PROMPT_SEPARATOR = ':';
  PROMPT_TAIL = '>';

  DATA_SEPARATOR: string = '&&';

  CMD_CLOSE = 'ext';
  CMD_CONTACT_LIST_ID = 'lstid';

  MAX_MSG_TRYS = 3; // ìàêñèìàëüíîå êîëè÷åñòâî ïîïûòîê ïåðåñûëà ïîñëå îøèáêè
  MAX_RESEND_TRYS = 9; // ìàêñèìàëüíîå êîëè÷åñòâî ïîïûòîê ïåðåñûëà â òàéìåðå
  MIN_TIME_BETWEEN_MSG = 30; // âðåìÿ ìåæäó îòïðàâêîé ñîîáùåíèé ñèñòåìå IM â ìñ

  OWNER_ID = 0;

(*
function TConnector.FSendMessage(const vMessage: string): boolean;
const
  LAST_SEND_TIME: TDateTime = 0.0;
var
  _now: TDateTime;
begin
  _now := Now;
  if (MilliSecondsBetween(_now, LAST_SEND_TIME) < MIN_TIME_BETWEEN_MSG) then
    Result := FALSE
  else
  begin
    LAST_SEND_TIME := _now;
    CallContactService(_hContact, PSS_MESSAGE, 0, LPARAM(PChar(vMessage)));
    Result := TRUE;
  end;
end;
*)

// PP: Let's hope Miranda IM can messages to different contacts at the same time

function TConnector.FSendMessage(const vMessage: string): boolean;
// const
//  LAST_SEND_TIME: TDateTime = 0.0;
var
  _now: TDateTime;
begin
  _now := Now;
  if (MilliSecondsBetween(_now, m_LastSendTime) < MIN_TIME_BETWEEN_MSG) then
    Result := FALSE
  else
  begin
    m_LastSendTime := _now;
    CallContactService(_hContact, PSS_MESSAGE, 0, LPARAM(PChar(vMessage)));
    Result := TRUE;
  end;
end;


function NotifySender(wParam: WPARAM; lParam_: LPARAM): int; cdecl;
const
  MSG_TRYS: integer = 1;
var
  connector: TConnector;
  hContact: THandle;
begin
  Result := 0;
  hContact := PACKDATA(lParam_).hContact;

  if (PACKDATA(lParam_).type_ <> ACKTYPE_MESSAGE) then
    exit;

  case PACKDATA(lParam_)^.result_ of
    ACKRESULT_SUCCESS:
    begin
      MSG_TRYS := 1;

      connector := g_connectorList.GetFirstConnector(hContact);
      while Assigned(connector) do
      begin
        if (connector._msg_sending <> '') then
          connector.FNotifySender;
        connector := g_connectorList.GetNextConnector;
     end;
    end;

    ACKRESULT_FAILED:
    begin
      inc(MSG_TRYS);
      if (MSG_TRYS <= MAX_MSG_TRYS) then
        begin
          connector := g_connectorList.GetFirstConnector(hContact);
          while (Assigned(connector)) do
          begin
            if connector._msg_sending <> '' then
              with connector do
              begin
                _msg_buf := _unformated_msg_sending + _msg_buf;
                _sendTimer.Enabled := TRUE;
              end;
            connector := g_connectorList.GetNextConnector;
          end; // while
        end
      else
      begin
        connector := g_connectorList.GetFirstConnector(hContact);
        while (Assigned(connector)) do
        begin
          if (connector._msg_sending <> '') then
          begin
            connector.FPluginConnectorHandler(ceError);
          end;
          connector := g_connectorList.GetNextConnector;
        end;
      end; // if (MSG_TRYS <= MAX_MSG_TRYS)
    end; // ACKRESULT_FAILED
  end; // case PACKDATA
end;


procedure TConnector.FNotifySender;
begin
{$IFDEF DEBUG_LOG}
  WriteToLog('<< ' + _msg_sending);
{$ENDIF}
  if (Connected and (_msg_sending <> MSG_INVITATION)) then
  begin
    _unformated_msg_sending := '';
    inc(_cntrMsgOut);
    if (_cntrMsgOut > m_iLastCntrMsgOutInFormatting) then
      _cntrMsgOut := m_iLastCntrMsgOutInFormatting + 1;
  end;
  _msg_sending := '';
end;


// äåôîðìàòèðîâàíèå âõîäÿùèõ ñîîáùåíèé. TRUE - åñëè äåêîäèðîâàíèå óäàëîñü
function TConnector.FDeformatMsg(var msg: string; out lstId, msgCntr: integer): boolean;
var
  l: integer;
begin
  Result := FALSE;
  if LeftStr(msg, length(PROMPT_HEAD + PROMPT_SEPARATOR)) = (PROMPT_HEAD + PROMPT_SEPARATOR) then
  begin
    msg := RightStr(msg, length(msg) - length(PROMPT_HEAD + PROMPT_SEPARATOR));

    // contactListId
//      if (_contactLstId >= 0) then
    if (g_bMultiSession) then
    begin
      l := pos(PROMPT_SEPARATOR, msg);
      if (l > 0) then
      begin
        if (not TryStrToInt(LeftStr(msg, l - 1), lstId)) then
          exit;
        msg := RightStr(msg, length(msg) - l);
      end
      else
        lstId := g_connectorList.LastAddedConnector._lstId;
    end
    else
      lstId := -1; // no contactListId specified in message

    // Message counter
    l := pos(PROMPT_TAIL, msg);
    if ((l = 0) or (not TryStrToInt(LeftStr(msg, l - 1), msgCntr))) then
      exit;

    msg := RightStr(msg, length(msg) - l);
    // msg := AnsiReplaceStr(msg, '&amp;', '&');

    Result := TRUE;
  end;
end;


function TConnector.FFilterMsg(msg: string): boolean;

  procedure NProceedData(msg: string);

    function NProceedSystemCommand(msg: string): boolean;
    begin
      Result := TRUE;
      if (LeftStr(msg, length(CMD_CONTACT_LIST_ID)) = CMD_CONTACT_LIST_ID) then
      begin
        msg := RightStr(msg, length(msg) - length(CMD_CONTACT_LIST_ID) - 1);
        TryStrToInt(msg, _contactLstId);
      end
      else if (msg = CMD_CLOSE) then
      begin
        FPluginConnectorHandler(ceDisconnected);
        _connected := FALSE;
        _opened := FALSE;
      end
      else
        Result := FALSE;
    end;

  var
    n, l, i: integer;
    arrDatas: TStringDynArray;
    strCommand: string;
    bSystemCommand: boolean;
  begin { \NProceedData }
    if (RightStr(msg, length(DATA_SEPARATOR)) <> DATA_SEPARATOR) then
      msg := msg + DATA_SEPARATOR;

    n := -1;
    l := 1;
    repeat
      inc(n);
      l := PosEx(DATA_SEPARATOR, msg, l);
      inc(l, length(DATA_SEPARATOR));
    until (l = length(DATA_SEPARATOR));

    SetLength(arrDatas, n);

    bSystemCommand := TRUE;
    i := 0;
    while (i < n) do
    begin
      l := pos(DATA_SEPARATOR, msg);
      strCommand := LeftStr(msg, l - 1);

      if (bSystemCommand) then // System commands can go only in the beginning by definition
      begin
        bSystemCommand := NProceedSystemCommand(strCommand);
        if (bSystemCommand) then
        begin
          dec(n);
          SetLength(arrDatas, n);
          continue;
        end;
      end;

      arrDatas[i] := strCommand;
      msg := RightStr(msg, length(msg) - length(DATA_SEPARATOR) - l + 1);

      inc(i);
    end; { while }

    if (n > 0) then
    begin
      FPluginConnectorHandler(ceData, arrDatas);
    end;

    Finalize(arrDatas);
  end;

var
  lstId, cntrMsg: integer;
begin { TConnector.FFilterMsg }
{$IFDEF DEBUG_LOG}
  WriteToLog('>> ' + msg);
{$ENDIF}
  if (not Connected) then
  begin
 // if (msg = MSG_INVITATION) or (msg = MSG_RESPOND) then
    if (msg = MSG_INVITATION) then
    begin
   // if msg = MSG_INVITATION then
   //   FSendMessage(MSG_RESPOND);
      FSendSystemData(MSG_INVITATION);
      if (g_bMultiSession) then
        FSendSystemData(FFormatMsg(CMD_CONTACT_LIST_ID + ' ' + IntToStr(_lstId)));
      _connected := TRUE;
      FPluginConnectorHandler(ceConnected);
      Result := TRUE;
    end
    else
      Result := FALSE;
  end
  else // Connected
  begin
    if (FDeformatMsg(msg, lstId, cntrMsg) and ((not g_bMultisession) or (lstId = _lstId))) then
    begin
      Result := TRUE;

      if (cntrMsg > _cntrMsgIn) then
      begin
        inc(_cntrMsgIn);
        if (cntrMsg > _cntrMsgIn) then
        begin
          FPluginConnectorHandler(ceError); // ïàêåò èñ÷åç
          exit;
        end;
      end
      else if (cntrMsg < _cntrMsgIn) then
        exit; // skipping packets with lower numbers

      // if (cntrMsg = _cntrMsgIn) there's no garantee that packets are synchronized, but let's hope it's so.

      NProceedData(msg);
    end
    else
      Result := FALSE;
  end;
end;


function TConnector.FFormatMsg(const msg: string): string;
var
  contactLstIdStr: string;
begin
  if (_contactLstId >= 0) then
    contactLstIdStr := PROMPT_SEPARATOR + IntToStr(_contactLstId)
  else // -1
    contactLstIdStr := '';
  Result := PROMPT_HEAD + contactLstIdStr + PROMPT_SEPARATOR + IntToStr(_cntrMsgOut) + PROMPT_TAIL + msg;
  m_iLastCntrMsgOutInFormatting := _cntrMsgOut;
end;


procedure TConnector.Close;
begin
  if (Connected) then
  begin
    FSendSystemData(FFormatMsg(CMD_CLOSE));

    _connected := FALSE;
    FPluginConnectorHandler(ceDisconnected);
  end;

  _sendTimer.Enabled := FALSE;
  _opened := FALSE;

{$IFDEF DEBUG_LOG}
  CloseLog;
{$ENDIF}
end;


function TConnector.Open(bMultiSession: boolean = TRUE): boolean;
var
  AConnector: TConnector;
begin
  Result := FALSE;

  if (not g_bMultiSession) then
    g_bMultiSession := bMultisession;

  if (Assigned(g_connectorList)) then
  begin
    AConnector := g_connectorList.GetFirstConnector(_hContact);
    while (Assigned(AConnector)) do
    begin
      if (AConnector.Opened and (AConnector._contactLstId < 0)) then
        exit;
      AConnector := g_connectorList.GetNextConnector;
    end;
  end;

  _cntrMsgIn := 0;
  _cntrMsgOut := 1;
  _msg_sending := '';
  _unformated_msg_sending := '';
  _msg_buf := '';
  _contactLstId := -1;
  _opened := TRUE;

  FSendSystemData(MSG_INVITATION);

  Result := TRUE;
end;


function TConnector.SendData(const d: string): boolean;
begin
  Result := FALSE;
  if (d = '') or
     (length(_msg_buf) + length(d) + length(DATA_SEPARATOR) > g_msgBufferSize) or
     (LeftStr(d, length(CMD_CLOSE)) = CMD_CLOSE) or
     (LeftStr(d, length(CMD_CONTACT_LIST_ID)) = CMD_CONTACT_LIST_ID) or
     (pos(DATA_SEPARATOR, d) > 0) then
  begin
    exit;
  end
  else
  begin
    _msg_buf := _msg_buf + d + DATA_SEPARATOR;
    _sendTimer.Enabled := TRUE; // Îòîñëàòü ñîîáùåíèå ñ íåêîòîðîé îòòÿæêîé -> âñ¸ îäíèì ïàêåòîì
  end;
  Result := TRUE;  
end;


function FilterMsg(wParam: WPARAM; lParam_: LPARAM): int; cdecl;
var
  msg: string;
  hContact: THandle;
  connector: TConnector;
  proceeded: boolean;
begin
  msg := string(PPROTORECVEVENT(PCCSDATA(lParam_).lParam).szMessage);
  hContact := PCCSDATA(lParam_).hContact;

  proceeded := FALSE;

  if Assigned(g_connectorList) then
  begin
    connector := g_connectorList.GetFirstConnector(hContact);
    while (Assigned(connector)) do
    begin
      if connector.Opened then
        proceeded := (connector.FFilterMsg(msg) or proceeded);
      connector := g_connectorList.GetNextConnector;
    end;
  end;

  if proceeded then
    Result := 0
  else
    Result := CallService(MS_PROTO_CHAINRECV, wParam, lParam_);
end;


constructor TConnector.Create(hContact: THandle);
const
  ID_COUNTER: Longword = 0;
var
  connector: TConnector;
begin
//  inherited Create;
  _sendTimer := TTimer.Create(nil);
  with _sendTimer do
  begin
    Enabled := FALSE;
    Interval := 100;
    OnTimer := FsendTimerTimer;
  end;

  _sendSystemTimer := TTimer.Create(nil);
  with _sendSystemTimer do
  begin
    Enabled := FALSE;
    Interval := 50;
    OnTimer := FsendSystemTimerTimer;
  end;

  _hContact := hContact;
  _systemDataList := TStringList.Create;

  if (not Assigned(g_connectorList)) then
    g_connectorList := TConnectorList.Create;

  connector := g_connectorList.GetFirstConnector(_hContact);
  if Assigned(connector) then
    _hFilterMsg := connector._hFilterMsg
  else
  begin
    _hFilterMsg := CreateProtoServiceFunction(PChar(PLUGIN_NAME), PSR_MESSAGE, FilterMsg);
    if CallService(MS_PROTO_ISPROTOONCONTACT, _hContact, LPARAM(PChar(PLUGIN_NAME))) = 0 then
      CallService(MS_PROTO_ADDTOCONTACT, _hContact, LPARAM(PChar(PLUGIN_NAME)));
  end;

  if (g_connectorList.Count = 0) then
    g_hNotifySender := HookEvent(ME_PROTO_ACK, NotifySender);

  inc(ID_COUNTER);
  m_lwId := ID_COUNTER;

  g_connectorList.AddConnector(self);

{$IFDEF DEBUG_LOG}
  InitLog;
{$ENDIF}
end;


destructor TConnector.Destroy;
begin
  if Connected then
    while (not FSendMessage(FFormatMsg(CMD_CLOSE))) do
      Sleep(1);

  _systemDataList.Free;

  g_connectorList.RemoveConnector(self);
  if (g_connectorList.Count = 0) then
    g_bMultiSession := FALSE;

  if (not Assigned(g_connectorList.GetFirstConnector(_hContact))) then
  begin
    if CallService(MS_PROTO_ISPROTOONCONTACT, _hContact, LPARAM(PChar(PLUGIN_NAME))) <> 0 then
      CallService(MS_PROTO_REMOVEFROMCONTACT, _hContact, LPARAM(PChar(PLUGIN_NAME)));
    PluginLink.DestroyServiceFunction(_hFilterMsg);
  end;

  if (g_connectorList.Count = 0) then
  begin
    if (g_hNotifySender <> 0) then
      UnhookEvent(g_hNotifySender);
    FreeAndNil(g_connectorList);
  end;

  _sendSystemTimer.Free;
  _sendTimer.Free;

{$IFDEF DEBUG_LOG}
  CloseLog;
{$ENDIF}

  inherited;
end;

{$IFDEF DEBUG_LOG}
procedure TConnector.InitLog;
begin
  AssignFile(_logFile, MirandaPluginPath + 'Chess4Net_CONNECTORLOG.txt');
  Append(_logFile);
  if IOResult <> 0 then
    begin
      Rewrite(_logFile);
      if IOResult <> 0 then
        begin
          AssignFile(_logFile, MirandaPluginPath + 'Chess4Net_CONNECTORLOG~.txt');
          Append(_logFile);
          if IOResult <> 0 then Rewrite(_logFile);
        end;
    end;

   WriteToLog('[' + DateTimeToStr(Now) + ']');
end;


procedure TConnector.WriteToLog(const s: string);
begin
  writeln(_logFile, s);
  Flush(_logFile);
end;


procedure TConnector.CloseLog;
begin
  CloseFile(_logFile);
end;
{$ENDIF}

procedure TConnector.FsendTimerTimer(Sender: TObject);
const
  RESEND_COUNT : integer = 0;
begin
  if (_systemDataList.Count > 0) then
    exit; // System data goes first

  if (_msg_sending = '') then
  begin
    _sendTimer.Enabled := FALSE;
    if (_msg_buf <> '') then
    begin
      _unformated_msg_sending := _msg_buf;
      _msg_sending := FFormatMsg(_msg_buf);
      _msg_buf := '';

      _sendTimer.Enabled := (not FSendMessage(_msg_sending));
    end;
  end
  else
  begin
{$IFDEF DEBUG_LOG}
    WriteToLog('resend: ' + _msg_sending);
{$ENDIF}
    inc(RESEND_COUNT);
    if (RESEND_COUNT = MAX_RESEND_TRYS) then
    begin
      RESEND_COUNT := 0;
      FSendMessage(_msg_sending);
    end;
  end;
end;


procedure TConnector.SetPlugin(plugin: IConnectorable);
begin
  _plugin := plugin;
end;


function TConnector.FGetOwnerNick: string;
begin
  Result := PChar(CallService(MS_CLIST_GETCONTACTDISPLAYNAME, 0, 0));
end;


function TConnector.FGetContactNick: string;
begin
  Result := PChar(CallService(MS_CLIST_GETCONTACTDISPLAYNAME, _hContact, 0));
end;


procedure InitConnectorGlobals(const invitationStr, promtHeadStr, dataSeparator: string; maxMsgSize: integer = 256);
begin
  MSG_INVITATION := invitationStr;
  PROMPT_HEAD := promtHeadStr;
  DATA_SEPARATOR := dataSeparator;
  g_msgBufferSize := maxMsgSize;
end;

{---------------------------- TConnectorList ---------------------------------}

procedure TConnectorList.AddConnector(Connector: TConnector);
var
  i: integer;
begin
  for i := 0 to Count - 1 do
  begin
    if (not Assigned(Items[i])) then
    begin
      Connector._lstId := i;
      Items[i] := Connector;
      exit;
    end;
  end; // for
  Add(Connector);
  Connector._lstId := Count - 1;
end;


procedure TConnectorList.RemoveConnector(Connector: TConnector);
begin
  Items[Connector._lstId] := nil;
  while ((Count > 0) and (not Assigned(Items[Count - 1]))) do
    Delete(Count - 1);
end;


function TConnectorList.GetFirstConnector(hContact: THandle): TConnector;
begin
  _hContact := hContact;

  _iterator := -1;
  Result := GetNextConnector;
end;


function TConnectorList.GetNextConnector: TConnector;
begin
  Result := nil;

  while (_iterator < (Count - 1)) do
  begin
    inc(_iterator);
    if (Assigned(Items[_iterator]) and
       (_hContact = TConnector(Items[_iterator])._hContact)) then
    begin
      Result := Items[_iterator];
      exit;
    end;
  end;
end;


function TConnectorList.FGetLastAddedConnector: TConnector;
var
  i: integer;
begin
  Result := nil;
  for i := 0 to Count - 1 do
  begin
    if ((not Assigned(Result)) or (TConnector(Items[i]).m_lwId > Result.m_lwId)) then
    Result := Items[i];
  end;
end;


procedure TConnector.FSendSystemData(sd: string);
begin
  if ((sd <> MSG_INVITATION) and (sd <> CMD_CLOSE)) then
    sd := sd + DATA_SEPARATOR;
  _systemDataList.Add(sd);
  _sendSystemTimer.Enabled := TRUE;
end;


procedure TConnector.FsendSystemTimerTimer(Sender: TObject);
begin
  if _systemDataList.Count = 0 then
    begin
      _sendSystemTimer.Enabled := FALSE;
      exit;
    end;

  _msg_sending := _systemDataList[0];
  if FSendMessage(_msg_sending) then
    _systemDataList.Delete(0);
  // else: try to resend
end;


function TConnector.FGetOwnerID: integer;
begin
  Result := OWNER_ID;
end;


procedure TConnector.FSetMultiSession(bValue: boolean);
begin
  if ((not g_bMultiSession) and bValue) then
  begin
    FSendSystemData(FFormatMsg(CMD_CONTACT_LIST_ID + ' ' + IntToStr(_lstId)));
    g_bMultiSession := TRUE;
  end;
end;

procedure TConnector.FPluginConnectorHandler(ce: TConnectorEvent;
  d1: pointer = nil; d2: pointer = nil);
begin
  if (Assigned(_plugin)) then
    _plugin.ConnectorHandler(ce, d1, d2); 
end;


function TConnector.FGetMultiSession: boolean;
begin
  Result := g_bMultiSession;
end;

end.