1 /* coded by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
2 * Understanding is not required. Only obedience.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 module accobj
is aliced
;
23 import arsd
.simpledisplay
;
43 // ////////////////////////////////////////////////////////////////////////// //
44 __gshared
bool optShowOffline
= false;
47 // ////////////////////////////////////////////////////////////////////////// //
48 __gshared string accBaseDir
= ".";
49 __gshared Contact activeContact
;
52 private bool decodeHexStringInto (ubyte[] dest
, const(char)[] str) {
55 foreach (char ch
; str) {
56 if (ch
<= ' ') continue;
58 if (ch
>= '0' && ch
<= '9') dig
= ch
-'0';
59 else if (ch
>= 'A' && ch
<= 'F') dig
= ch
-'A'+10;
60 else if (ch
>= 'a' && ch
<= 'f') dig
= ch
-'a'+10;
62 if (dpos
>= dest
.length
*2) return false;
63 if (dpos
%2 == 0) dest
[dpos
/2] = cast(ubyte)(dig
<<16); else dest
[dpos
/2] |
= cast(ubyte)dig
;
66 return (dpos
== dest
.length
*2);
70 public PubKey
decodePubKeyStr (const(char)[] str) {
72 if (!decodeHexStringInto(res
[], str)) res
[] = toxCoreEmptyKey
[];
77 public ToxAddr
decodeAddrStr (const(char)[] str) {
79 if (!decodeHexStringInto(res
[], str)) res
[] = toxCoreEmptyAddr
[];
84 // ////////////////////////////////////////////////////////////////////////// //
87 this (Account aOwner
) nothrow { acc
= aOwner
; }
90 bool mDirty
; // true: write contact's config
98 void markDirty () pure nothrow @safe @nogc => mDirty
= true;
101 import std
.path
: dirName
;
103 assert(acc
!is null);
105 if (diskFileName
.length
== 0) {
106 diskFileName
= acc
.basePath
~"/contacts/groups.rc";
108 mkdirRec(diskFileName
.dirName
);
109 if (serialize(info
, diskFileName
)) mDirty
= false;
112 @property bool visible () const nothrow @trusted @nogc {
113 if (!hideIfNoVisibleMembers
) return true; // always visible
114 // check if we have any visible members
115 foreach (const(Contact
) c
; acc
.contacts
.byValue
) {
116 if (c
.gid
!= info
.gid
) continue;
117 if (c
.visibleNoGroupCheck
) return true;
119 return false; // nobody's here
122 private bool getTriOpt(string
fld, string fld2
=null) () const nothrow @trusted @nogc {
123 enum lo
= "info."~fld;
124 if (mixin(lo
) != TriOption
.Default
) return (mixin(lo
) == TriOption
.Yes
);
125 static if (fld2
.length
) return mixin("acc.info."~fld2
); else return mixin("acc.info."~fld);
128 private int getIntOpt(string
fld) () const nothrow @trusted @nogc {
129 enum lo
= "info."~fld;
130 if (mixin(lo
) >= 0) return mixin(lo
);
131 return mixin("acc.info."~fld);
134 @property nothrow @safe {
135 uint gid () const pure @nogc => info
.gid
;
137 bool opened () const @nogc => info
.opened
;
138 void opened (bool v
) @nogc { pragma(inline
, true); if (info
.opened
!= v
) { info
.opened
= v
; markDirty(); } }
140 string
name () const @nogc => info
.name
;
141 void name (string v
) @nogc { pragma(inline
, true); if (v
.length
== 0) v
= "<unnamed>"; if (info
.name
!= v
) { info
.name
= v
; markDirty(); } }
143 string
note () const @nogc => info
.note
;
144 void note (string v
) @nogc { pragma(inline
, true); if (info
.note
!= v
) { info
.note
= v
; markDirty(); } }
147 bool showOffline () const => getTriOpt
!"showOffline";
148 bool showPopup () const => getTriOpt
!"showPopup";
149 bool blinkActivity () const => getTriOpt
!"blinkActivity";
150 bool skipUnread () const => getTriOpt
!"skipUnread";
151 bool hideIfNoVisibleMembers () const => getTriOpt
!("hideIfNoVisibleMembers", "hideEmptyGroups");
152 bool ftranAllowed () const => getTriOpt
!"ftranAllowed";
153 int resendRotDays () const => getIntOpt
!"resendRotDays";
154 int hmcOnOpen () const => getIntOpt
!"hmcOnOpen";
160 // ////////////////////////////////////////////////////////////////////////// //
161 final class Contact
{
163 // `Connecting` for non-account means "awaiting authorization"
166 bool isMe
; // "/me" message?
169 long msgid
; // ==0: unknown yet
172 string
textOrig () const pure nothrow @trusted @nogc {
174 while (pos
< text
.length
&& text
.ptr
[pos
] != ']') ++pos
;
176 return (pos
< text
.length ? text
[pos
..$] : null);
179 bool isOurMark (const(void)[] atext
, SysTime atime
) nothrow @trusted {
180 pragma(inline
, true);
181 return (atime
== time
&& textDigest(textOrig
) == textDigest(atext
));
184 bool isOurMark (long aid
, const(void)[] atext
, SysTime atime
) nothrow @trusted {
185 pragma(inline
, true);
186 return (aid
> 0 ?
(msgid
== aid
) : (atime
== time
&& textDigest(textOrig
) == textDigest(atext
)));
189 bool isOurMark (long aid
, in ref TextDigest adigest
, SysTime atime
) nothrow @trusted {
190 pragma(inline
, true);
191 return (aid
> 0 ?
(msgid
== aid
) : (atime
== time
&& textDigest(textOrig
) == adigest
));
196 MonoTime nextSendTime
; // for resend queue
199 this (Account aOwner
) nothrow { acc
= aOwner
; edit
= new MiniEdit(); }
201 void removeData () nothrow {
202 if (diskFileName
.length
== 0) return;
204 import std
.file
: rmdirRecurse
, rename
;
205 import std
.path
: dirName
;
206 auto dn
= diskFileName
.dirName
;
207 if (dn
.length
== 0 || dn
== "/") return; // just in case
208 conwriteln("removing dir <", dn
, ">");
213 } catch (Exception e
) {}
217 bool mDirty
; // true: write contact's config
223 ContactStatus status
= ContactStatus
.Offline
; // not saved, so if it safe to change it
229 void markDirty () pure nothrow @safe @nogc => mDirty
= true;
231 void loadUnreadCount () nothrow {
232 assert(diskFileName
.length
);
233 assert(acc
!is null);
235 import std
.path
: dirName
;
236 auto fi
= VFile(diskFileName
.dirName
~"/logs/unread.dat");
237 unreadCount
= fi
.readNum
!int;
238 } catch (Exception e
) {
243 void saveUnreadCount () nothrow {
244 assert(diskFileName
.length
);
245 assert(acc
!is null);
247 import std
.path
: dirName
;
248 auto fo
= VFile(diskFileName
.dirName
~"/logs/unread.dat", "w");
249 fo
.writeNum(unreadCount
);
250 } catch (Exception e
) {
254 void loadResendQueue () {
255 import std
.path
: dirName
;
256 string fname
= diskFileName
.dirName
~"/logs/resend.log";
259 foreach (const ref lmsg
; lf
.messages
) {
261 xmsg
.isMe
= lmsg
.isMe
;
262 xmsg
.time
= lmsg
.time
;
263 xmsg
.text
= lmsg
.text
;
267 nextSendTime
= MonoTime
.currTime
;
270 void saveResendQueue () {
271 import std
.file
: remove
;
272 import std
.path
: dirName
;
273 assert(diskFileName
.length
);
274 assert(acc
!is null);
275 mkdirRec(diskFileName
.dirName
~"/logs");
276 string fname
= diskFileName
.dirName
~"/logs/resend.log";
277 try { remove(fname
); } catch (Exception e
) {}
278 if (resendQueue
.length
) {
279 foreach (const ref msg
; resendQueue
) {
280 LogFile
.appendLine(fname
, LogFile
.Msg
.Kind
.Outgoing
, msg
.text
, msg
.isMe
, msg
.time
);
286 import std
.path
: dirName
;
288 assert(acc
!is null);
290 if (diskFileName
.length
== 0) {
291 diskFileName
= acc
.basePath
~"/contacts/"~tox_hex(info
.pubkey
[])~"/config.rc";
292 acc
.contacts
[info
.pubkey
] = this;
294 mkdirRec(diskFileName
.dirName
);
295 mkdirRec(diskFileName
.dirName
~"/avatars");
296 mkdirRec(diskFileName
.dirName
~"/files");
297 mkdirRec(diskFileName
.dirName
~"/fileparts");
298 mkdirRec(diskFileName
.dirName
~"/logs");
300 if (serialize(info
, diskFileName
)) mDirty
= false;
309 @property bool visibleNoGroupCheck () const nothrow @trusted @nogc => (!kfd
&& (optShowOffline || showOffline || acceptPending || requestPending || status
!= ContactStatus
.Offline || unreadCount
> 0));
311 @property bool visible () const nothrow @trusted @nogc {
312 if (kfd
) return false;
313 if (acceptPending || requestPending
) return true;
314 if (unreadCount
> 0) return true;
315 if (!showOffline
&& !optShowOffline
&& status
== ContactStatus
.Offline
) return false;
316 auto grp
= acc
.groupById(gid
);
317 return (grp
.visible
&& grp
.opened
);
320 @property nothrow @safe {
321 bool online () const pure @nogc => (status
!= ContactStatus
.Offline
&& status
!= ContactStatus
.Connecting
);
323 ContactInfo
.Kind
kind () const @nogc => info
.kind
;
324 void kind (ContactInfo
.Kind v
) @nogc { pragma(inline
, true); if (info
.kind
!= v
) { info
.kind
= v
; markDirty(); } }
326 uint gid () const @nogc => info
.gid
;
327 void gid (uint v
) @nogc { pragma(inline
, true); if (info
.gid
!= v
) { info
.gid
= v
; markDirty(); } }
329 string
nick () const @nogc => info
.nick
;
330 void nick (string v
) @nogc { pragma(inline
, true); if (info
.nick
!= v
) { info
.nick
= v
; markDirty(); } }
332 string
visnick () const @nogc => info
.visnick
;
333 void visnick (string v
) @nogc { pragma(inline
, true); if (info
.visnick
!= v
) { info
.visnick
= v
; markDirty(); } }
335 string
displayNick () const @nogc => (info
.visnick
.length ? info
.visnick
: (info
.nick
.length ? info
.nick
: "<unknown>"));
337 string
statusmsg () const @nogc => info
.statusmsg
;
338 void statusmsg (string v
) @nogc { pragma(inline
, true); if (info
.statusmsg
!= v
) { info
.statusmsg
= v
; markDirty(); } }
340 bool kfd () const @nogc => (info
.kind
== ContactInfo
.Kind
.KillFuckDie
);
341 bool friend () const @nogc => (info
.kind
== ContactInfo
.Kind
.Friend
);
342 bool acceptPending () const @nogc => (info
.kind
== ContactInfo
.Kind
.PengingAuthAccept
);
343 bool requestPending () const @nogc => (info
.kind
== ContactInfo
.Kind
.PengingAuthRequest
);
345 void setLastOnlineNow () {
347 auto ut
= systimeNow
.toUnixTime();
348 if (info
.lastonlinetime
!= cast(uint)ut
) { info
.lastonlinetime
= cast(uint)ut
; markDirty(); }
349 } catch (Exception e
) {}
352 string
note () const @nogc => info
.note
;
353 void note (string v
) @nogc { pragma(inline
, true); if (info
.note
!= v
) { info
.note
= v
; markDirty(); } }
356 private bool getTriOpt(string
fld) () const nothrow @trusted @nogc {
357 enum lo
= "info.opts."~fld;
358 if (mixin(lo
) != TriOption
.Default
) return (mixin(lo
) == TriOption
.Yes
);
359 auto grp
= acc
.groupById(info
.gid
);
360 enum go
= "grp.info."~fld;
361 if (mixin(go
) != TriOption
.Default
) return (mixin(go
) == TriOption
.Yes
);
362 return mixin("acc.info."~fld);
365 private int getIntOpt(string
fld) () const nothrow @trusted @nogc {
366 enum lo
= "info.opts."~fld;
367 if (mixin(lo
) >= 0) return mixin(lo
);
368 auto grp
= acc
.groupById(info
.gid
);
369 enum go
= "grp.info."~fld;
370 if (mixin(go
) >= 0) return mixin(go
);
371 return mixin("acc.info."~fld);
374 @property nothrow @safe @nogc {
375 bool showOffline () const => !kfd
&& getTriOpt
!"showOffline";
376 bool showPopup () const => !kfd
&& getTriOpt
!"showPopup";
377 bool blinkActivity () const => !kfd
&& getTriOpt
!"blinkActivity";
378 bool skipUnread () const => kfd || getTriOpt
!"skipUnread";
379 bool ftranAllowed () const => !kfd
&& getTriOpt
!"ftranAllowed";
380 int resendRotDays () const => getIntOpt
!"resendRotDays";
381 int hmcOnOpen () const => getIntOpt
!"hmcOnOpen";
384 void loadLogInto (ref LogFile lf
) {
385 import std
.file
: exists
;
386 import std
.path
: dirName
;
387 string lname
= diskFileName
.dirName
~"/logs/hugelog.log";
388 if (lname
.exists
) lf
.load(lname
); else lf
.clear();
391 void appendToLog (LogFile
.Msg
.Kind kind
, const(char)[] text
, bool isMe
, SysTime time
) {
392 import std
.path
: dirName
;
393 string lname
= diskFileName
.dirName
~"/logs/hugelog.log";
394 LogFile
.appendLine(lname
, kind
, text
, isMe
, time
);
397 void ackReceived (long msgid
) {
398 if (msgid
<= 0) return; // wtf?!
399 bool changed
= false;
401 while (idx
< resendQueue
.length
) {
402 if (resendQueue
[idx
].msgid
== msgid
) {
403 foreach (immutable c
; idx
+1..resendQueue
.length
) resendQueue
[c
-1] = resendQueue
[c
];
404 resendQueue
[$-1] = XMsg
.init
;
405 resendQueue
.length
-= 1;
406 resendQueue
.assumeSafeAppend
;
412 if (changed
) saveResendQueue();
416 long findInResendQueue (const(char)[] text
, SysTime time
) {
417 foreach (ref XMsg msg
; resendQueue
) {
418 if (msg
.time
== time
&& msg
.textOrig
== text
) {
419 //conwriteln("<", text, "> found in resend queue; id=", msg.msgid, "; rt=<", msg.text, ">");
421 } /*else if (msg.textOrig == text) {
422 conwriteln("<", text, "> (", time, ":", msg.time, ") IS NOT: id=", msg.msgid, "; rt=<", msg.text, ">");
428 bool removeFromResendQueue (long msgid
, in ref TextDigest digest
, SysTime time
) {
431 while (pos
< resendQueue
.length
) {
432 if (resendQueue
[pos
].isOurMark(msgid
, digest
, time
)) {
433 foreach (immutable c
; pos
+1..resendQueue
.length
) resendQueue
[c
-1] = resendQueue
[c
];
434 resendQueue
[$-1] = XMsg
.init
;
435 resendQueue
.length
-= 1;
436 resendQueue
.assumeSafeAppend
;
442 if (doSave
) saveResendQueue();
446 // called when toxcore goes offline
447 void resetQueueIds () {
448 foreach (ref XMsg msg
; resendQueue
) msg
.msgid
= 0;
449 if (activeContact
is this) logResetAckMessageIds();
450 nextSendTime
= MonoTime
.currTime
+30.seconds
;
453 void processResendQueue () {
454 if (status
== ContactStatus
.Offline || status
== ContactStatus
.Connecting
) return;
456 foreach (ref XMsg msg
; resendQueue
) {
457 long msgid
= toxCoreSendMessage(acc
.toxpk
, info
.pubkey
, msg
.text
, msg
.isMe
);
458 if (msgid
< 0) break;
459 if (activeContact
is this) logFixAckMessageId(msg
.msgid
, msgid
, msg
.textOrig
, msg
.time
);
461 if (msg
.resendCount
++ != 0) doSave
= true;
463 if (doSave
) saveResendQueue();
464 nextSendTime
= MonoTime
.currTime
+30.seconds
;
467 void send (const(char)[] text
) {
468 void sendOne (const(char)[] text
, bool action
) {
469 if (text
.length
== 0) return; // just in case
471 SysTime now
= systimeNow
;
472 long msgid
= toxCoreSendMessage(acc
.toxpk
, info
.pubkey
, text
, action
);
473 if (msgid
< 0) { conwriteln("ERROR sending message to '", info
.nick
, "'"); return; }
475 // add this to resend queue
479 xmsg
.msgid
= msgid
; // 0: we are offline
480 xmsg
.resendCount
= 0;
482 auto ctt
= MonoTime
.currTime
;
483 if (nextSendTime
<= ctt
) nextSendTime
= ctt
+30.seconds
;
487 import std
.format
: format
;
488 auto dt = cast(DateTime
)now
;
489 xmsg
.text
= "[%04u/%02u/%02u %02u:%02u:%02u] %s".format(dt.year
, dt.month
, dt.day
, dt.hour
, dt.minute
, dt.second
, text
);
494 if (activeContact
is this) addTextToLog(acc
, this, LogFile
.Msg
.Kind
.Outgoing
, action
, text
, now
, msgid
);
495 appendToLog(LogFile
.Msg
.Kind
.Outgoing
, text
, action
, now
);
498 bool action
= text
.startsWith("/me ");
499 if (action
) text
= text
[4..$].xstripleft
;
501 while (text
.length
) {
502 auto ep
= text
.indexOf('\n');
503 if (ep
< 0) ep
= text
.length
; else ++ep
; // include '\n'
504 // remove line if it contains only spaces
505 bool hasNonSpace
= false;
506 foreach (immutable char ch
; text
[0..ep
]) if (ch
> ' ') { hasNonSpace
= true; break; }
507 if (hasNonSpace
) break;
510 while (text
.length
&& text
[$-1] <= ' ') text
= text
[0..$-1];
511 if (text
.length
== 0) return; // nothing to do
514 //TODO: split at word boundaries
515 enum ReservedSpace
= 23+3+3;
517 // k8: toxcore developers are idiots, so we have to do dynalloc here
518 auto tmpbuf
= new char[](tox_max_message_length()+64);
519 scope(exit
) delete tmpbuf
;
522 while (text
.length
) {
523 int epos
= tox_max_message_length()-ReservedSpace
;
524 if (epos
< text
.length
) {
527 if (text
[epos
-1] < 128) break;
528 if ((text
[epos
-1]&0xc0) == 0xc0) break;
532 epos
= cast(int)text
.length
;
535 if (first
&& epos
>= text
.length
) {
536 sendOne(text
[0..epos
], action
);
539 if (!first
) { tmpbuf
[0..3] = "..."; ofs
= 3; }
540 tmpbuf
[ofs
..ofs
+epos
] = text
[0..epos
];
541 tmpbuf
[ofs
+epos
..ofs
+epos
+3] = "...";
542 sendOne(tmpbuf
[0..ofs
+epos
+3], action
);
545 text
= text
[epos
..$];
553 // ////////////////////////////////////////////////////////////////////////// //
554 final class Account
{
556 void saveGroups () nothrow {
557 import std
.algorithm
: sort
;
558 GroupOptions
[] glist
;
559 scope(exit
) delete glist
;
560 foreach (Group g
; groups
) glist
~= g
.info
;
561 glist
.sort
!((in ref a
, in ref b
) => a
.gid
< b
.gid
);
562 glist
.serialize(basePath
~"contacts/groups.rc");
565 void saveUpdatedGroups () {
566 bool needToUpdate
= false;
567 foreach (Group g
; groups
) if (g
.mDirty
) { needToUpdate
= true; g
.mDirty
= false; }
568 if (needToUpdate
) saveGroups();
572 ContactStatus mStatus
= ContactStatus
.Offline
;
575 PubKey toxpk
= toxCoreEmptyKey
;
576 string toxDataDiskName
;
577 string basePath
; // with trailing "/"
578 ProtoOptions protoOpts
;
581 Contact
[PubKey
] contacts
;
584 bool mIAmConnecting
= false;
585 bool mIAmOnline
= false;
586 bool forceOnline
= true; // set to `false` to stop autoreconnecting
589 @property bool isConnecting () const nothrow @safe @nogc => mIAmConnecting
;
591 @property bool isOnline () const nothrow @safe @nogc {
592 if (!toxpk
.isValidKey
) return false;
593 if (mIAmConnecting
) return false;
594 if (!mIAmOnline
) return false;
598 @property ContactStatus
status () const nothrow @safe @nogc {
599 if (!toxpk
.isValidKey
) return ContactStatus
.Offline
;
600 if (mIAmConnecting
) return ContactStatus
.Connecting
;
601 if (!mIAmOnline
) return ContactStatus
.Offline
;
605 @property void status (ContactStatus v
) {
606 if (!toxpk
.isValidKey
) return;
607 conwriteln("changing status to ", v
, " (old: ", mStatus
, ")");
608 if (v
== ContactStatus
.Connecting
) v
= ContactStatus
.Online
;
609 forceOnline
= (v
!= ContactStatus
.Offline
);
610 if (mStatus
== ContactStatus
.Offline
) {
611 if (v
!= ContactStatus
.Offline
) mIAmConnecting
= true;
613 toxCoreSetStatus(toxpk
, v
);
615 glconPostScreenRepaint();
619 void processResendQueue () {
620 if (!isOnline
) return;
621 foreach (Contact ct
; contacts
.byValue
) { ct
.processResendQueue(); ct
.update(); }
625 void saveResendQueue () {
626 foreach (Contact ct
; contacts
.byValue
) { ct
.saveResendQueue(); ct
.update(); }
632 toxpk
= toxCoreOpenAccount(toxDataDiskName
);
633 if (!toxpk
.isValidKey
) {
634 conwriteln("creating new Tox account...");
635 string nick
= info
.nick
;
636 if (nick
.length
> 0) {
638 if (nick
.length
> tox_max_name_length()) nick
= nick
[0..tox_max_name_length()];
642 toxpk
= toxCoreCreateAccount(toxDataDiskName
, nick
);
643 if (!toxpk
.isValidKey
) throw new Exception("cannot create Tox account");
645 conwriteln("my address: [", tox_hex(toxCoreGetSelfAddress(toxpk
)), "]");
646 toxLoadKnownContacts();
649 // load contacts from ToxCore data and add 'em to contact database
650 void toxLoadKnownContacts () {
651 if (!toxpk
.isValidKey
) return;
653 toxCoreForEachFriend(toxpk
, delegate (in ref PubKey self
, in ref PubKey frpub
, scope const(char)[] anick
) {
654 string nick
= anick
.buildNormalizedString
!true;
655 auto c
= (frpub
in contacts ? contacts
[frpub
] : null);
657 conwriteln("NEW friend with pk [", tox_hex(frpub
), "]; name is: ", nick
);
658 c
= new Contact(this);
661 c
.info
.pubkey
[] = frpub
[];
662 c
.info
.opts
.showOffline
= TriOption
.Default
;
663 auto ls
= toxCoreLastSeen(self
, frpub
);
664 if (ls
!= SysTime
.min
) {
665 c
.info
.lastonlinetime
= cast(uint)ls
.toUnixTime();
667 if (c
.info
.lastonlinetime
== 0 && nick
.length
== 0) {
668 c
.info
.kind
= ContactInfo
.Kind
.PengingAuthRequest
;
670 contacts
[c
.info
.pubkey
] = c
;
673 if (clist
!is null) clist
.buildAccount(this);
675 bool needSave
= false;
676 auto ls
= toxCoreLastSeen(self
, frpub
);
677 if (ls
!= SysTime
.min
) {
678 auto lsu
= cast(uint)ls
.toUnixTime();
679 if (c
.info
.lastonlinetime
!= lsu
) { c
.info
.lastonlinetime
= lsu
; needSave
= true; }
681 if (c
.info
.nick
!= nick
) {
682 conwriteln("OLD friend with pk [", tox_hex(frpub
), "]; new name is: ", nick
);
683 if (c
.info
.nick
.length
== 0 && nick
.length
!= 0) {
688 conwriteln("OLD friend with pk [", tox_hex(frpub
), "]; old name is: ", nick
);
690 if (needSave
) c
.save();
692 return false; // don't stop
696 auto data
= toxCoreLoadDataFile(VFile(toxDataDiskName
));
697 foreach (const ref ci
; data
.friends
) {
698 auto c
= (ci
.pubkey
in contacts ? contacts
[ci
.pubkey
] : null);
700 conwriteln("NEW friend with pk [", tox_hex(ci
.pubkey
), "]; name is: ", ci
.nick
);
701 c
= new Contact(this);
703 c
.info
.nick
= ci
.nick
;
704 c
.info
.statusmsg
= ci
.statusmsg
;
705 c
.info
.lastonlinetime
= ci
.lastonlinetime
;
706 c
.info
.kind
= ci
.kind
;
707 c
.info
.pubkey
[] = ci
.pubkey
[];
708 c
.info
.opts
.showOffline
= TriOption
.Default
;
709 contacts
[c
.info
.pubkey
] = c
;
712 if (clist
!is null) clist
.buildAccount(this);
714 bool needSave
= false;
716 if (c
.info
.nick
!= ci
.nick
) {
717 conwriteln("OLD friend with pk [", tox_hex(ci
.pubkey
), "]; new name is: ", ci
.nick
);
719 conwriteln("OLD friend with pk [", tox_hex(ci
.pubkey
), "]; old name is: ", ci
.nick
);
722 if (c
.info
.kind
!= ci
.kind
) { c
.info
.kind
= ci
.kind
; needSave
= true; }
723 if (c
.info
.lastonlinetime
!= ci
.lastonlinetime
) { c
.info
.lastonlinetime
= ci
.lastonlinetime
; needSave
= true; }
724 if (c
.info
.nick
.length
== 0 && ci
.nick
.length
!= 0) { c
.info
.nick
= ci
.nick
; needSave
= true; }
725 if (needSave
) c
.save();
728 } catch (Exception e
) {}
733 bool sendFriendRequest (in ref ToxAddr fraddr
, const(char)[] msg
) {
734 if (!toxpk
.isValidKey
) return false;
735 if (!isValidAddr(fraddr
)) return false;
736 if (msg
.length
== 0) return false;
737 if (msg
.length
> tox_max_friend_request_length()) return false;
738 if (!toxCoreSendFriendRequest(toxpk
, fraddr
, msg
)) return false;
739 PubKey frpub
= fraddr
[0..PubKey
.length
];
740 auto c
= (frpub
in contacts ? contacts
[frpub
] : null);
742 c
= new Contact(this);
744 c
.info
.nick
= null; // unknown yet
745 c
.info
.pubkey
[] = frpub
[];
746 c
.info
.opts
.showOffline
= TriOption
.Default
;
747 c
.info
.kind
= ContactInfo
.Kind
.PengingAuthRequest
;
748 c
.info
.fraddr
[] = fraddr
[]; // save address, just in case
749 contacts
[c
.info
.pubkey
] = c
;
752 if (clist
!is null) clist
.buildAccount(this);
758 // connection established
759 void toxConnectionDropped () {
761 conprintfln("TOX[%s] CONNECTION DROPPED", timp
.srvalias
);
762 mIAmConnecting
= false;
764 auto oldst
= mStatus
;
765 toxCoreSetStatus(toxpk
, ContactStatus
.Offline
); // this kills toxcore instance
766 foreach (Contact ct
; contacts
.byValue
) {
767 ct
.status
= ContactStatus
.Offline
;
768 if (ct
.kfd
) toxCoreRemoveFriend(toxpk
, ct
.info
.pubkey
);
769 // this is not quite correct: we need to distinguish when user goes offline, and when toxcore temporarily goes offline
770 // but we're killing toxcore instance on disconnect, so it works
774 mStatus
= ContactStatus
.Offline
;
777 glconPostScreenRepaint();
780 // connection established
781 void toxConnectionEstablished () {
783 conprintfln("TOX[%s] CONNECTION ESTABLISHED", timp
.srvalias
);
784 mIAmConnecting
= false;
786 if (info
.statusmsg
.length
== 0) info
.statusmsg
= "Come taste the gasoline! [BioAcid]";
787 toxCoreSetStatusMessage(toxpk
, info
.statusmsg
);
788 //toxLoadKnownContacts();
789 glconPostScreenRepaint();
792 void toxFriendOffline (in ref PubKey fpk
) {
793 if (auto ct
= fpk
in contacts
) {
794 auto ls
= toxCoreLastSeen(toxpk
, fpk
);
795 if (ls
!= SysTime
.min
) {
796 auto lsu
= cast(uint)ls
.toUnixTime();
797 if (ct
.info
.lastonlinetime
!= lsu
) { ct
.info
.lastonlinetime
= lsu
; ct
.markDirty(); glconPostScreenRepaint(); }
799 if (ct
.status
!= ContactStatus
.Offline
) {
800 conwriteln("friend <", ct
.info
.nick
, "> gone offline");
801 ct
.status
= ContactStatus
.Offline
;
802 glconPostScreenRepaint();
807 void toxSelfStatus (ContactStatus cst
) {
808 if (mStatus
!= cst
) {
810 glconPostScreenRepaint();
814 void toxFriendStatus (in ref PubKey fpk
, ContactStatus cst
) {
815 if (auto ct
= fpk
in contacts
) {
817 if (ct
.status
!= cst
) {
818 conwriteln("status for friend <", ct
.info
.nick
, "> changed to ", cst
);
819 auto ls
= toxCoreLastSeen(toxpk
, fpk
);
820 if (ls
!= SysTime
.min
) {
821 auto lsu
= cast(uint)ls
.toUnixTime();
822 if (ct
.info
.lastonlinetime
!= lsu
) { ct
.info
.lastonlinetime
= lsu
; ct
.markDirty(); }
825 // if it is online, and it is not a friend, turn it into a friend
826 if (ct
.online
&& !ct
.friend
) ct
.kind
= ContactInfo
.Kind
.Friend
;
827 if (ct
.online
) ct
.processResendQueue(); // why not?
828 glconPostScreenRepaint();
833 void toxFriendStatusMessage (in ref PubKey fpk
, string msg
) {
834 if (auto ct
= fpk
in contacts
) {
836 if (ct
.info
.statusmsg
!= msg
) {
837 conwriteln("status message for friend <", ct
.info
.nick
, "> changed to <", msg
, ">");
838 ct
.info
.statusmsg
= msg
;
840 if (ct
.showPopup
) showPopup(PopupWindow
.Kind
.Status
, ct
.nick
, (msg
.length ? msg
: "<nothing>"));
841 glconPostScreenRepaint();
846 void toxFriendNickChanged (in ref PubKey fpk
, string nick
) {
847 if (auto ct
= fpk
in contacts
) {
848 nick
= nick
.xstrip();
849 if (nick
.length
&& ct
.info
.nick
!= nick
) {
850 auto onick
= ct
.info
.nick
;
853 if (ct
.showPopup
) showPopup(PopupWindow
.Kind
.Status
, ct
.nick
, "changed nick to '"~nick
~"' from '"~onick
~"'");
854 glconPostScreenRepaint();
859 void toxFriendReqest (in ref PubKey fpk
, const(char)[] msg
) {
861 conprintfln("TOX[%s] FRIEND REQUEST FROM [%s]: <%s>", timp
.srvalias
, tox_hex(fpk
[]), msg
);
862 if (auto ct
= fpk
in contacts
) {
864 // if not waiting for acceptance, force-friend it
865 if (!ct
.acceptPending
) {
866 conwriteln("force-friend <", ct
.info
.nick
, ">");
867 toxCoreAddFriend(toxpk
, fpk
);
869 ct
.kind
= ContactInfo
.Kind
.PengingAuthAccept
;
870 ct
.info
.statusmsg
= msg
.idup
;
872 ct
.setLastOnlineNow();
874 showPopup(PopupWindow
.Kind
.Info
, "Friend Accepted", (msg
.length ? msg
: "<nothing>"));
876 // new friend request
877 conwriteln("AUTH REQUEST from pk [", tox_hex(fpk
), "]");
878 auto c
= new Contact(this);
881 c
.info
.pubkey
[] = fpk
[];
882 c
.info
.opts
.showOffline
= TriOption
.Default
;
883 c
.info
.statusmsg
= msg
.idup
;
884 c
.kind
= ContactInfo
.Kind
.PengingAuthAccept
;
885 contacts
[c
.info
.pubkey
] = c
;
886 c
.setLastOnlineNow();
888 showPopup(PopupWindow
.Kind
.Info
, "Friend Request", (msg
.length ? msg
: "<nothing>"));
890 if (clist
!is null) clist
.buildAccount(this);
892 glconPostScreenRepaint();
895 void toxFriendMessage (in ref PubKey fpk
, bool action
, string msg
, SysTime time
) {
896 if (auto ct
= fpk
in contacts
) {
897 bool doPopup
= ct
.showPopup
;
898 LogFile
.Msg
.Kind kind
= LogFile
.Msg
.Kind
.Incoming
;
899 ct
.appendToLog(kind
, msg
, action
, time
);
900 if (*ct
is activeContact
) {
901 // if inactive or invisible, add divider line and increase unread count
902 if (!mainWindowVisible ||
!mainWindowActive
) {
903 if (ct
.unreadCount
== 0) addDividerLine();
905 ct
.saveUnreadCount();
909 addTextToLog(this, *ct
, kind
, action
, msg
, time
);
912 ct
.saveUnreadCount();
914 if (doPopup
) showPopup(PopupWindow
.Kind
.Incoming
, ct
.nick
, msg
);
918 // ack for sent message
919 void toxMessageAck (in ref PubKey fpk
, long msgid
) {
921 conprintfln("TOX[%s] ACK MESSAGE FROM [%s]: %u", timp
.srvalias
, tox_hex(fpk
[]), msgid
);
922 if (auto ct
= fpk
in contacts
) {
923 if (*ct
is activeContact
) ackLogMessage(msgid
);
924 ct
.ackReceived(msgid
);
929 @property string
srvalias () const pure nothrow @safe @nogc => info
.nick
;
933 serialize(info
, basePath
~"config.rc");
937 this (string aBaseDir
) {
938 import std
.algorithm
: sort
;
939 import std
.file
: DirEntry
, SpanMode
, dirEntries
;
940 import std
.path
: baseName
;
942 basePath
= normalizeBaseDir(aBaseDir
);
943 toxDataDiskName
= basePath
~"toxdata.tox";
944 protoOpts
.txtunser(VFile(basePath
~"proto.rc"));
945 info
.txtunser(VFile(basePath
~"config.rc"));
948 GroupOptions
[] glist
;
949 glist
.txtunser(VFile(basePath
~"contacts/groups.rc"));
950 bool hasDefaultGroup
= false;
951 bool hasMoronsGroup
= false;
952 foreach (ref GroupOptions gi
; glist
[]) {
953 auto g
= new Group(this);
956 foreach (ref gg
; groups
[]) if (gg
.gid
== g
.gid
) { delete gg
; gg
= g
; found
= true; }
957 if (!found
) groups
~= g
;
958 if (g
.gid
== 0) hasDefaultGroup
= true;
959 if (g
.gid
== g
.gid
.max
-2) hasMoronsGroup
= true;
962 // create default group if necessary
963 if (!hasDefaultGroup
) {
967 gi
.note
= "default group for new contacts";
969 auto g
= new Group(this);
974 // create morons group if necessary
975 if (!hasMoronsGroup
) {
977 gi
.gid
= gi
.gid
.max
-2;
978 gi
.name
= "<morons>";
979 gi
.note
= "group for completely ignored dumbfucks";
981 gi
.showOffline
= TriOption
.No
;
982 gi
.showPopup
= TriOption
.No
;
983 gi
.blinkActivity
= TriOption
.No
;
984 gi
.skipUnread
= TriOption
.Yes
;
985 gi
.hideIfNoVisibleMembers
= TriOption
.Yes
;
986 gi
.ftranAllowed
= TriOption
.No
;
987 gi
.resendRotDays
= 0;
989 auto g
= new Group(this);
995 groups
.sort
!((in ref a
, in ref b
) => a
.gid
< b
.gid
);
997 if (!hasDefaultGroup ||
!hasMoronsGroup
) saveGroups();
999 static bool isValidCDName (const(char)[] str) {
1000 if (str.length
!= 64) return false;
1001 foreach (immutable char ch
; str) {
1002 if (ch
>= '0' && ch
<= '9') continue;
1003 if (ch
>= 'A' && ch
<= 'F') continue;
1004 if (ch
>= 'a' && ch
<= 'f') continue;
1011 foreach (DirEntry
de; dirEntries(basePath
~"contacts", SpanMode
.shallow
)) {
1012 if (de.name
.baseName
== "." ||
de.name
.baseName
== ".." ||
!isValidCDName(de.name
.baseName
)) continue;
1014 import std
.file
: exists
;
1015 if (!de.isDir
) continue;
1016 string cfgfn
= de.name
~"/config.rc";
1017 if (!cfgfn
.exists
) continue;
1019 ci
.txtunser(VFile(cfgfn
));
1020 auto c
= new Contact(this);
1021 c
.diskFileName
= cfgfn
;
1023 contacts
[c
.info
.pubkey
] = c
;
1024 c
.loadResendQueue();
1025 c
.loadUnreadCount();
1026 // fix contact group
1027 if (groupById
!false(c
.gid
) is null) {
1028 c
.info
.gid
= 0; // move to default group
1031 //conwriteln("loaded contact [", c.info.nick, "] from '", c.diskFileName, "'");
1032 } catch (Exception e
) {
1033 conwriteln("ERROR loading contact from '", de.name
, "/config.rc'");
1038 assert(toxpk
.isValidKey
, "something is VERY wrong here");
1039 conwriteln("created ToxCore for [", tox_hex(toxpk
[]), "]");
1043 if (toxpk
.isValidKey
) {
1044 toxCoreCloseAccount(toxpk
);
1045 toxpk
[] = toxCoreEmptyKey
[];
1049 // will not write contact to disk
1050 Contact
createEmptyContact () {
1051 auto c
= new Contact(this);
1053 c
.info
.nick
= "test contact";
1054 c
.info
.pubkey
[] = 0;
1058 // returns `null` if there is no such group, and `dofail` is `true`
1059 inout(Group
) groupById(bool dofail
=true) (uint agid
) inout nothrow @nogc {
1060 foreach (const Group g
; groups
) if (g
.gid
== agid
) return cast(inout)g
;
1061 static if (dofail
) assert(0, "group not found"); else return null;
1064 int opApply () (scope int delegate (ref Contact ct
) dg
) {
1065 foreach (Contact ct
; contacts
.byValue
) if (auto res
= dg(ct
)) return res
;
1069 // returns gid, or uint.max on error
1070 uint findGroupByName (const(char)[] name
) nothrow {
1071 if (name
.length
== 0) return uint.max
;
1072 foreach (const Group g
; groups
) if (g
.name
== name
) return g
.gid
;
1076 // returns gid, or uint.max on error
1077 uint createGroup(T
:const(char)[]) (T name
) nothrow {
1078 if (name
.length
== 0) return uint.max
;
1079 // groups are sorted by gid, yeah
1081 foreach (const Group g
; groups
) {
1082 if (g
.name
== name
) return g
.gid
;
1083 if (newgid
== g
.gid
) newgid
= g
.gid
+1;
1085 if (newgid
== uint.max
) return uint.max
;
1089 static if (is(T
== string
)) gi
.name
= name
; else gi
.name
= name
.idup
;
1091 auto g
= new Group(this);
1094 import std
.algorithm
: sort
;
1095 groups
.sort
!((in ref a
, in ref b
) => a
.gid
< b
.gid
);
1100 // returns `false` on any error
1101 bool moveContactToGroup (Contact ct
, uint gid
) nothrow {
1102 if (ct
is null || gid
== uint.max
) return false;
1103 // check if this is our contact
1105 foreach (Contact cc
; contacts
.byValue
) if (cc
is ct
) { found
= true; break; }
1106 if (!found
) return false;
1109 foreach (Group g
; groups
) if (g
.gid
== gid
) { grp
= g
; break; }
1110 if (grp
is null) return false;
1112 if (ct
.info
.gid
!= gid
) {
1119 // returns `false` on any error
1120 bool removeContact (Contact ct
) nothrow {
1121 if (ct
is null ||
!isOnline
) return false;
1122 // check if this is our contact
1124 foreach (Contact cc
; contacts
.byValue
) if (cc
is ct
) { found
= true; break; }
1125 if (!found
) return false;
1126 if (!toxCoreRemoveFriend(toxpk
, ct
.info
.pubkey
)) return false;
1128 contacts
.remove(ct
.info
.pubkey
);
1130 ct.kind = ContactInfo.Kind.KillFuckDie;
1137 static string
normalizeBaseDir (string aBaseDir
) {
1138 import std
.path
: absolutePath
, expandTilde
;
1139 if (aBaseDir
.length
== 0 || aBaseDir
== "." || aBaseDir
[$-1] == '/') throw new Exception("invalid base dir");
1140 if (aBaseDir
.indexOf('/') < 0) aBaseDir
= "~/.bioacid/"~aBaseDir
;
1141 aBaseDir
= aBaseDir
.expandTilde
.absolutePath
;
1142 if (aBaseDir
[$-1] != '/') aBaseDir
~= '/';
1147 static Account
CreateNew (string aBaseDir
, string aAccName
) {
1148 aBaseDir
= normalizeBaseDir(aBaseDir
);
1149 mkdirRec(aBaseDir
~"contacts");
1150 // write protocol options
1153 serialize(popt
, aBaseDir
~"proto.rc");
1158 acc
.nick
= aAccName
;
1159 acc
.showPopup
= true;
1160 acc
.blinkActivity
= true;
1161 acc
.hideEmptyGroups
= false;
1162 acc
.ftranAllowed
= true;
1163 acc
.resendRotDays
= 4;
1165 serialize(acc
, aBaseDir
~"config.rc");
1167 // create default group
1169 GroupOptions
[1] grp
;
1171 grp
[0].name
= "default";
1172 grp
[0].opened
= true;
1173 //grp[0].hideIfNoVisible = TriOption.Yes;
1174 serialize(grp
[], aBaseDir
~"contacts/groups.rc");
1177 return new Account(aBaseDir
);
1182 // ////////////////////////////////////////////////////////////////////////// //
1183 void setupToxEventListener (SimpleWindow sdmain
) {
1184 assert(sdmain
!is null);
1186 sdmain
.addEventListener((ToxEventBase evt
) {
1187 auto acc
= clist
.accountByPK(evt
.self
);
1189 if (acc
is null) return;
1191 bool fixTray
= false;
1192 scope(exit
) { if (fixTray
) fixTrayIcon(); glconPostScreenRepaint(); }
1195 if (auto e
= cast(ToxEventConnection
)evt
) {
1196 if (e
.who
[] == acc
.toxpk
[]) {
1197 if (e
.connected
) acc
.toxConnectionEstablished(); else acc
.toxConnectionDropped();
1200 if (!e
.connected
) acc
.toxFriendOffline(e
.who
);
1205 if (auto e
= cast(ToxEventStatus
)evt
) {
1206 if (e
.who
[] == acc
.toxpk
[]) {
1207 acc
.toxSelfStatus(e
.status
);
1210 acc
.toxFriendStatus(e
.who
, e
.status
);
1215 if (auto e
= cast(ToxEventStatusMsg
)evt
) {
1216 if (e
.who
[] != acc
.toxpk
[]) acc
.toxFriendStatusMessage(e
.who
, e
.message
);
1220 if (auto e
= cast(ToxEventNick
)evt
) {
1221 if (e
.who
[] != acc
.toxpk
[]) acc
.toxFriendNickChanged(e
.who
, e
.nick
);
1224 // incoming text message?
1225 if (auto e
= cast(ToxEventMessage
)evt
) {
1226 if (e
.who
[] != acc
.toxpk
[]) {
1227 acc
.toxFriendMessage(e
.who
, e
.action
, e
.message
, e
.time
);
1232 // ack outgoing text message?
1233 if (auto e
= cast(ToxEventMessageAck
)evt
) {
1234 if (e
.who
[] != acc
.toxpk
[]) acc
.toxMessageAck(e
.who
, e
.msgid
);
1238 //glconProcessEventMessage();