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
|
#!/usr/bin/env python3
"""
Syncthing-GTK - Daemon
Class interfacing with syncthing daemon
Create instance, connect singal handlers and call daemon.reconnect()
"""
import json
import logging
import os
import sys
import time
import urllib.parse
from datetime import datetime
from xml.dom import minidom
from dateutil import tz
from gi.repository import Gio, GLib, GObject
from syncthing_gtk.http import (
HTTP_HEADERS,
ConnectionRestarted,
EventPollLoop,
HTTPAuthException,
HTTPCode,
HTTPError,
InvalidConfigurationException,
InvalidHTTPResponse,
RESTPOSTRequest,
RESTRequest,
TLSErrorException,
TLSUnsupportedException,
)
from syncthing_gtk.timermanager import TimerManager
from syncthing_gtk.tools import compare_version, get_config_dir, get_header, parsetime
log = logging.getLogger("Daemon")
# Minimal version supported by Daemon class
MIN_VERSION = "0.14"
# Last-seen values before this date are translated to never
NEVER = datetime(1971, 1, 1, 1, 1, 1, tzinfo=tz.tzlocal())
class Daemon(GObject.GObject, TimerManager):
"""
Object for interacting with syncthing daemon.
List of signals:
config-out-of-sync ()
Emitted when daemon synchronization gets out of sync and
daemon needs to be restarted.
config-saved ()
Emitted when daemon saves configuration without need for
restarting.
connected ()
Emitted when connection to daemon is initiated, before
configuration is loaded and parsed.
disconnected (reason, message)
Emitted after connection to daemon is lost. Connection can
be reinitiated by calling reconnect()
reason : Daemon.SHUTDOWN if connection is closed
after calling shutdown()
Daemon.RESTART if connection is closed
after calling restart()
Daemon.UNEXPECTED for all other cases
message: generated error message
config-loaded(config)
Emitted while connection do daemon is being created, when
configuration is loaded from daemon.
config: decoded /rest/config YAML file
connection-error (reason, message, exception)
Emitted if connection to daemon fails.
reason: Daemon.REFUSED if connection is refused and
daemon probably offline. Connection will be
retried automatically.
Daemon.UNKNOWN for all other problems.
Connection can be reinitiated by calling
reconnect() in this case.
message: generated error message
exception: Exeception that caused problem or None
my-id-changed (my_id, replaced)
Emitted when ID is retrieved from device or when ID changes
after client connects to another device
my_id: ID of device that is instance connected to.
error (message)
Emitted every time when daemon generates error readable by
WebUI (/rest/errors call)
message: Error message sent by daemon
folder-rejected(device_id, folder_id, label)
Emitted when daemon detects unexpected folder from known
device.
device_id: id of device that send unexpected folder id
folder_id: id of unexpected folder
label: label of unexpected folder or None
device-rejected(device_id, device_name, address)
Emitted when daemon detects connection from unknown device
device_id: device id
device_name: device name
address: address which connection come from
device-added (id, name, used, data)
Emited when new device is loaded from configuration
id: id of loaded device
name: name of loaded device (may be None)
used: true if there is any folder shared with this device
data: dict with rest of device data
device-connected (id)
Emitted when daemon connects to remote device
id: id of device
device-disconnected (id)
Emitted when daemon loses connection to remote device
id: id of device
device-discovered (id, addresses)
# TODO: What this event does?
id: id of device
addresses: list of device addresses
device-data-changed (id, address, version, inbps, outbps, inbytes, outbytes)
Emitted when device data changes
id: id of device
address: address of remote device
version: daemon version of remote device
inbps: download rate
outbps: upload rate
inbytes: total number of bytes downloaded
outbytes: total number of bytes uploaded
last-seen-changed (id, last_seen)
Emitted when daemon reported 'last seen' value for device changes
or when is this value received for first time
id: id of device
last_seen: datetime object or None, if device was never seen
device-paused (id):
Emitted when synchronization with device is paused
id: id of folder
device-resumed (id):
Emitted when synchronization with device is resumed
id: id of folder
device-sync-started (id, progress):
Emitted after device synchronization is started
id: id of folder
progress: synchronization progress (0.0 to 1.0)
device-sync-progress (id, progress):
Emitted repeatedly while device is being synchronized
id: id of folder
progress: synchronization progress (0.0 to 1.0)
device-sync-finished (id):
Emitted after device synchronization is finished
id: id of folder
folder-added (id, data)
Emitted when new folder is loaded from configuration
id: id of loaded folder
data: dict with rest of folder data
folder-error (id, errors)
Emitted when when a folder cannot be successfully synchronized
id: id of loaded folder
errors: list with errors
folder-data-changed (id, data):
Emitted when change in folder data (/rest/model call)
is detected and successfully loaded.
id: id of folder
data: dict with loaded data
folder-data-failed (id):
Emitted when daemon fails to load folder data (/rest/model call),
most likely because folder was just added and syncthing
daemon needs to be restarted
id: id of folder
folder-scan-progress (id, progress):
Emitted repeatedly while folder is being scanned
id: id of folder
progress: scan progress (0.0 to 1.0)
folder-sync-progress (id, progress):
Emitted repeatedly while folder is being synchronized
id: id of folder
progress: synchronization progress (0.0 to 1.0)
folder-sync-finished (id):
Emitted after folder synchronization is finished
id: id of folder
folder-scan-started (id):
Emitted after folder scan is started
id: id of folder
folder-scan-finished (id):
Emitted after folder scan is finished
id: id of folder
folder-stopped (id, message):
Emitted when folder enters 'stopped' state.
No 'folder-sync', 'folder-sync-progress' and 'folder-scan-started'
events are emitted after folder enters this state, until
reconnect() is called.
id: id of folder
message: error message
item-started (folder_id, filename, time):
Emitted when synchronization of file starts
folder_id: id of folder that contains file
filename: synchronized file
time: event timestamp
item-updated (folder_id, filename, time):
Emited when change in local file is detected (LocalIndexUpdated event)
folder_id: id of folder that contains file
filename: updated file
time: event timestamp
startup-complete():
Emited when daemon initialization is complete.
system-data-updated (ram_ussage, cpu_ussage, d_failed, d_total)
Emitted every time when system information is received
from daemon.
ram_ussage: memory ussage in bytes
cpu_ussage: CPU ussage in percent (0.0 to 100.0)
d_failed: Number of discovery servers that daemon failed to
connect to
d_total: Total number of discovery servers
"""
__gsignals__ = {
"config-out-of-sync": (GObject.SIGNAL_RUN_FIRST, None, ()),
"config-saved": (GObject.SIGNAL_RUN_FIRST, None, ()),
"connected": (GObject.SIGNAL_RUN_FIRST, None, ()),
"disconnected": (GObject.SIGNAL_RUN_FIRST, None, (int, object)),
"config-loaded": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"connection-error": (GObject.SIGNAL_RUN_FIRST, None, (int, object, object)),
"error": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"folder-rejected": (GObject.SIGNAL_RUN_FIRST, None, (object, object, object)),
"device-rejected": (GObject.SIGNAL_RUN_FIRST, None, (object, object, object)),
"my-id-changed": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"device-added": (GObject.SIGNAL_RUN_FIRST, None, (object, object, bool, object)),
"device-connected": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"device-disconnected": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"device-discovered": (GObject.SIGNAL_RUN_FIRST, None, (object, object,)),
"device-data-changed": (GObject.SIGNAL_RUN_FIRST, None, (object, object, object, float, float, object, object)),
"last-seen-changed": (GObject.SIGNAL_RUN_FIRST, None, (object, object)),
"device-paused": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"device-resumed": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"device-sync-started": (GObject.SIGNAL_RUN_FIRST, None, (object, float)),
"device-sync-progress": (GObject.SIGNAL_RUN_FIRST, None, (object, float)),
"device-sync-finished": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"folder-added": (GObject.SIGNAL_RUN_FIRST, None, (object, object)),
"folder-error": (GObject.SIGNAL_RUN_FIRST, None, (object, object)),
"folder-data-changed": (GObject.SIGNAL_RUN_FIRST, None, (object, object)),
"folder-data-failed": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"folder-sync-finished": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"folder-sync-progress": (GObject.SIGNAL_RUN_FIRST, None, (object, float)),
"folder-sync-started": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"folder-scan-finished": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"folder-scan-started": (GObject.SIGNAL_RUN_FIRST, None, (object,)),
"folder-scan-progress": (GObject.SIGNAL_RUN_FIRST, None, (object, float)),
"folder-stopped": (GObject.SIGNAL_RUN_FIRST, None, (object, object)),
"item-started": (GObject.SIGNAL_RUN_FIRST, None, (object, object, object)),
"item-updated": (GObject.SIGNAL_RUN_FIRST, None, (object, object, object)),
"startup-complete": (GObject.SIGNAL_RUN_FIRST, None, ()),
"system-data-updated": (GObject.SIGNAL_RUN_FIRST, None, (int, float, int, int)),
}
# Constants for 'reason' parameter of disconnected event
UNEXPECTED = 0 # connection closed by daemon
SHUTDOWN = 1
RESTART = 2
# Constants for 'reason' parameter of connection-error event
REFUSED = 1
NOT_AUTHORIZED = 2
OLD_VERSION = 3
TLS_UNSUPPORTED = 4
UNKNOWN = 255
def __init__(self, syncthing_configxml=None):
GObject.GObject.__init__(self)
TimerManager.__init__(self)
self._CSRFtoken = None
self._address = None
self._api_key = None
self._connected = False
self._refresh_interval = 1 # seconds
self._configxml = syncthing_configxml
# syncing_folders holds set of folders that are being synchronized
self._syncing_folders = set()
# stopped_folders holds set of folders in 'stopped' state
# No 'folder-sync', 'folder-sync-progress' and 'folder-scan-started'
# events are emitted after folder enters this state
self._stopped_folders = set()
# syncing_devices does same thing, only for devices
self._syncing_devices = set()
# and once again, for folders in 'Scanning' state
self._scanning_folders = set()
# device_data stores data needed to compute transfer speeds
# and synchronization state
self._device_data = {}
# folder_devices stores list of devices assigned to folder
self._folder_devices = {}
# last_seen holds last_seen value for each folder, preventing firing
# last-seen-changed event with same values twice
self._last_seen = {}
# last_error_time is used to discard repeating errors
self._last_error_time = None # Time is taken for first event
# last_id is id of last event received from daemon
self._last_id = 0
# Epoch is increased when reconnect() method is called; It is
# used to discard responses for old REST requests
self._epoch = 1
self._instance_id = None
self._my_id = None
self._read_config()
# Internal stuff
def _read_config(self):
# Read syncthing config to get connection url
if not self._configxml:
self._configxml = os.path.join(
get_config_dir(), "syncthing", "config.xml")
if not os.path.exists(self._configxml) and os.path.exists(os.path.expanduser("~/snap/syncthing/common/syncthing")):
# Special case for syncthing in snap package
self._configxml = os.path.expanduser(
"~/snap/syncthing/common/syncthing/config.xml")
try:
log.debug("Reading syncthing config %s", self._configxml)
with open(self._configxml, "r") as f:
config = f.read()
except Exception as e:
raise InvalidConfigurationException(
"Failed to read daemon configuration: %s" % e)
try:
xml = minidom.parseString(config)
except Exception as e:
raise InvalidConfigurationException(
"Failed to parse daemon configuration: %s" % e)
tls = "false"
try:
tls = xml.getElementsByTagName("configuration")[0] \
.getElementsByTagName("gui")[0].getAttribute("tls")
except Exception:
pass
self._tls = False
self._cert = None
if tls.lower() == "true":
self._tls = True
try:
self._cert = Gio.TlsCertificate.new_from_file(
os.path.join(get_config_dir(), "syncthing", "https-cert.pem"))
except Exception as e:
log.exception(e)
raise TLSErrorException("Failed to load daemon certificate")
try:
self._address = xml.getElementsByTagName("configuration")[0] \
.getElementsByTagName("gui")[0] \
.getElementsByTagName("address")[0] \
.firstChild.nodeValue
if self._address.startswith("0.0.0.0"):
addr, port = self._address.split(":", 1)
self._address = "127.0.0.1:%s" % (port,)
log.debug(
"WebUI listens on 0.0.0.0, connecting to 127.0.0.1 instead")
except Exception as e:
log.exception(e)
raise InvalidConfigurationException(
"Required configuration node not found in daemon config file")
try:
self._api_key = xml.getElementsByTagName("configuration")[0] \
.getElementsByTagName("gui")[0] \
.getElementsByTagName("apikey")[0] \
.firstChild.nodeValue
except Exception:
# API key can be none
pass
def override_config(self, address, api_key):
"""
Can be used to override settings loaded from config file.
api_key can be None.
"""
self._address = address
self.api_key = api_key
def _get_device_data(self, nid):
""" Returns dict with device data, creating it if needed """
if nid not in self._device_data:
self._device_data[nid] = {
"inBytesTotal": 0, "outBytesTotal": 0,
"inbps": 0, "outbps": 0, "clientVersion": "?",
"address": "", "completion": {}, "connected": False,
}
return self._device_data[nid]
def _request_config(self, *a):
""" Request settings from syncthing daemon """
RESTRequest(self, "system/config", self._syncthing_cb_config,
self._syncthing_cb_config_error).start()
def _request_folder_data(self, folder_id):
id_enc = urllib.parse.quote(folder_id.encode('utf-8'))
RESTRequest(self, "db/status?folder=%s" % (id_enc,), self._syncthing_cb_folder_data,
self._syncthing_cb_folder_data_failed, folder_id).start()
def _request_last_seen(self, *a):
""" Request 'last seen' values for all devices """
RESTRequest(self, "stats/device",
self._syncthing_cb_last_seen).ignore_error().start()
def _parse_dev_n_folders(self, config):
"""
Parses devices and folders from configuration and emits
associated events.
"""
# Pre-parse folders to detect unused devices
device_folders = {}
for r in config["folders"]:
rid = r["id"]
for n in r["devices"]:
nid = n["deviceID"]
if nid not in device_folders:
device_folders[nid] = []
device_folders[nid].append(rid)
# Parse devices
for n in sorted(config["devices"], key=lambda x: x["name"].lower()):
nid = n["deviceID"]
self._get_device_data(nid) # Creates dict with device data
used = (nid in device_folders) and (len(device_folders[nid]) > 0)
self.emit("device-added", nid, n["name"], used, n)
# Parse folders
for r in sorted(config["folders"], key=lambda x: x["id"].lower()):
rid = r["id"]
self._syncing_folders.add(rid)
self._folder_devices[rid] = [n["deviceID"] for n in r["devices"]]
self.emit("folder-added", rid, r)
self._request_folder_data(rid)
# Callbacks
def _syncthing_cb_shutdown(self, data, reason):
""" Callback for 'shutdown' AND 'restart' request """
if 'ok' in data:
if self._connected:
self._connected = False
self._epoch += 1
self.emit("disconnected", reason, "")
self.cancel_all()
def _syncthing_cb_errors(self, errors):
if errors["errors"] is not None:
for e in errors["errors"]:
if "time" in e:
# TODO: Remove this next time support for older daemon is dropped
t = parsetime(e["time"])
msg = e["error"]
elif "when" in e:
t = parsetime(e["when"])
msg = e["message"]
else:
# Can't decode this
continue
if t > self._last_error_time:
self.emit("error", msg)
self._last_error_time = t
r = RESTRequest(self, "system/error", self._syncthing_cb_errors)
self.timer("errors", self._refresh_interval * 5, r.start)
def _syncthing_cb_connections(self, data, prev_time):
now = time.time()
td = now - prev_time
cons = data["connections"]
# Use my own device for totals, if it is already known
# It it is not known, just skip totals for now
if self._my_id is not None:
cons[self._my_id].update(data["total"])
for id in cons:
# Load device data
nid = id
device_data = self._get_device_data(nid)
# Compute rates
try:
cons[id]["inbps"] = max(
0.0, (cons[id]["inBytesTotal"] - device_data["inBytesTotal"]) / td)
cons[id]["outbps"] = max(
0.0, (cons[id]["outBytesTotal"] - device_data["outBytesTotal"]) / td)
except Exception:
cons[id]["inbps"] = 0.0
cons[id]["outbps"] = 0.0
# Store updated device_data
for key in cons[id]:
if key not in ('clientVersion', 'connected'): # Don't want copy those
if cons[id][key] != "": # Happens for 'total'
device_data[key] = cons[id][key]
if "clientVersion" in cons[id] and cons[id]["clientVersion"] != "":
device_data["clientVersion"] = cons[id]["clientVersion"]
if cons[id]["paused"]:
# Send "device-paused" signal if device needed
device_data["connected"] = False
self.emit("device-paused", nid)
else:
# Send "device-connected" signal, if device was disconnected until now
if cons[id]["connected"]:
if not device_data["connected"] and nid != self._my_id:
device_data["connected"] = True
self.emit("device-connected", nid)
# Send "device-data-changed" signal
self.emit("device-data-changed", nid,
device_data["address"],
device_data["clientVersion"],
device_data["inbps"],
device_data["outbps"],
device_data["inBytesTotal"],
device_data["outBytesTotal"])
# ... repeat until pronounced dead
r = RESTRequest(self, "system/connections",
self._syncthing_cb_connections, None, now)
self.timer("conns", self._refresh_interval * 5, r.start)
def _syncthing_cb_last_seen(self, data):
for nid in data:
if nid != HTTP_HEADERS:
t = parsetime(data[nid]["lastSeen"])
if t < NEVER:
t = None
if nid not in self._last_seen or self._last_seen[nid] != t:
self._last_seen[nid] = t
self.emit('last-seen-changed', nid, t)
def _syncthing_cb_completion(self, data):
nid = data["device"]
rid = data["folder"]
# Store acquired value
device = self._get_device_data(nid)
device["completion"][rid] = float(data["completion"])
# Recompute stuff
total = 100.0 * len(device["completion"])
sync = 0.0
if total > 0.0:
sync = sum(device["completion"].values()) / total
if sync <= 0 or sync >= 100:
# Not syncing
if nid in self._syncing_devices:
self._syncing_devices.discard(nid)
self.emit("device-sync-finished", nid)
else:
# Syncing
if nid not in self._syncing_devices:
self._syncing_devices.add(nid)
self.emit("device-sync-started", nid, sync)
else:
self.emit("device-sync-progress", nid, sync)
def _syncthing_cb_system(self, data):
if "myID" not in data:
# Invalid response
r = RESTRequest(self, "system/status", self._syncthing_cb_system)
log.warning(
"Invalid response received for rest/system/status request")
self.timer("system", self._refresh_interval * 5, r.start)
return
if self._my_id != data["myID"]:
if self._my_id is not None:
# Can myID be ever changed?
log.warning("My ID has been changed on the fly")
self._my_id = data["myID"]
self.emit('my-id-changed', self._my_id)
version = get_header(data[HTTP_HEADERS], "X-Syncthing-Version")
if version:
self._syncthing_cb_version_known(version)
else:
RESTRequest(self, "system/version",
self._syncthing_cb_version).start()
d_failed, d_total = 0, 0
if "discoveryEnabled" in data and data["discoveryEnabled"]:
d_total = data["discoveryMethods"]
d_failed = len(data["discoveryErrors"])
if "startTime" in data:
if self._instance_id is None:
self._instance_id = data["startTime"]
else:
if self._instance_id != data["startTime"]:
return self._instance_replaced()
self.emit('system-data-updated', data["sys"],
float(data["cpuPercent"]), d_failed, d_total)
r = RESTRequest(self, "system/status", self._syncthing_cb_system)
self.timer("system", self._refresh_interval * 5, r.start)
def _instance_replaced(self):
"""
Called when it is detected that syncthing daemon instance is no longer
same as we talked to before
"""
log.warning(
"Daemon instance was replaced unexpectedly. Disconnecting from daemon.")
self._disconnected(message="Daemon instance replaced unexpectedly")
def _disconnected(self, reason=UNEXPECTED, message=""):
""" Called to prepare and emit "disconnected" signal """
self._my_id = None
if self._connected:
self._connected = False
self._epoch += 1
self.emit("disconnected", reason, message)
self.cancel_all()
def _syncthing_cb_version(self, data):
if "version" in data:
# New since https://github.com/syncthing/syncthing/commit/d7956dd4957fa6eee5971c072fd7181015fa876c
version = data["version"]
else:
version = data["data"]
self._syncthing_cb_version_known(version)
def _syncthing_cb_version_known(self, version):
"""
Called when version is received from daemon, either by
calling /rest/version or from X-Syncthing-Version header.
"""
if not compare_version(version, MIN_VERSION):
# Syncting version too low. Cancel everything and report error
self.cancel_all()
self._epoch += 1
msg = "daemon is too old"
self.emit("connection-error", Daemon.OLD_VERSION,
msg, Exception(msg))
return
if self._my_id is not None:
device = self._get_device_data(self._my_id)
if version != device["clientVersion"]:
device["clientVersion"] = version
self.emit("device-data-changed", self._my_id,
None,
device["clientVersion"],
device["inbps"], device["outbps"],
device["inBytesTotal"], device["outBytesTotal"])
def _syncthing_cb_folder_data(self, data, rid):
state = data['state']
if state in ('error', 'stopped'):
if rid not in self._stopped_folders:
self._stopped_folders.add(rid)
reason = data["invalid"] or data["error"]
self.emit("folder-stopped", rid, reason)
self.emit('folder-data-changed', rid, data)
p = 0.0
if state == "syncing":
if float(data["globalBytes"]) > 0.0:
p = float(data["inSyncBytes"]) / float(data["globalBytes"])
self._folder_state_changed(rid, state, p)
def _syncthing_cb_folder_data_failed(self, exception, request, rid):
self.emit('folder-data-failed', rid)
def _syncthing_cb_config(self, config):
"""
Called when configuration is loaded from syncthing daemon.
After configuration is successfully parsed, app starts querying for events
"""
if not self._connected:
self._connected = True
self.emit('connected')
self._parse_dev_n_folders(config)
EventPollLoop(self).start()
RESTRequest(self, "system/config/insync",
self._syncthing_cb_config_in_sync).start()
RESTRequest(self, "system/connections",
self._syncthing_cb_connections, None, time.time()).start()
RESTRequest(self, "system/status",
self._syncthing_cb_system).start()
self._request_last_seen()
self.check_config()
self.emit('config-loaded', config)
def _syncthing_cb_config_error(self, exception, command):
self.cancel_all()
if isinstance(exception, GLib.GError):
# Connection Refused / Cannot connect to destination
if exception.code in (0, 39, 34, 45):
# It usually means that daemon is not yet fully started or not running at all.
epoch = self._epoch
self.emit("connection-error", Daemon.REFUSED,
exception.message, exception)
if epoch == self._epoch:
r = RESTRequest(
self, "system/config", self._syncthing_cb_config, self._syncthing_cb_config_error)
self.timer("config", self._refresh_interval, r.start)
return
elif isinstance(exception, HTTPAuthException):
self.emit("connection-error", Daemon.NOT_AUTHORIZED,
exception.message, exception)
return
elif isinstance(exception, HTTPCode):
# HTTP 404 may actually mean old daemon version
version = get_header(exception.headers, "X-Syncthing-Version")
if version is not None and not compare_version(version, MIN_VERSION):
self._epoch += 1
msg = "daemon is too old"
self.emit("connection-error", Daemon.OLD_VERSION,
msg, Exception(msg))
else:
self.emit("connection-error", Daemon.UNKNOWN,
exception.message, exception)
return
elif isinstance(exception, TLSUnsupportedException):
self.emit("connection-error", Daemon.TLS_UNSUPPORTED,
exception.message, exception)
return
elif isinstance(exception, ConnectionRestarted):
# Happens on Windows. Just try again.
GLib.idle_add(self._request_config)
return
elif isinstance(exception, TLSUnsupportedException):
self.emit("connection-error", Daemon.TLS_UNSUPPORTED,
exception.message, exception)
return
self.emit("connection-error", Daemon.UNKNOWN,
exception.message, exception)
def _syncthing_cb_config_in_sync(self, data):
"""
Handler for config/sync response. Emits 'config-out-of-sync' if
configuration is not in sync.
"""
if "configInSync" in data:
if not data["configInSync"]:
# Not in sync...
self.emit("config-out-of-sync")
def _folder_state_changed(self, rid, state, progress):
"""
Emits event according to last known and new state.
"""
if state != "syncing" and rid in self._syncing_folders:
self._syncing_folders.discard(rid)
if rid not in self._stopped_folders:
self.emit("folder-sync-finished", rid)
if state != "scanning" and rid in self._scanning_folders:
self._scanning_folders.discard(rid)
if rid not in self._stopped_folders:
self.emit("folder-scan-finished", rid)
if state == "syncing":
if rid not in self._stopped_folders:
if rid in self._syncing_folders:
self.emit("folder-sync-progress", rid, progress)
else:
self._syncing_folders.add(rid)
self.emit("folder-sync-started", rid)
elif state == "scanning":
if rid not in self._stopped_folders:
if rid not in self._scanning_folders:
self._scanning_folders.add(rid)
self.emit("folder-scan-started", rid)
def _on_event(self, e):
eType = e["type"]
if eType in ("Ping", "Starting"):
# Just ignore ignore those
pass
elif eType == "StartupComplete":
self.emit("startup-complete")
elif eType == "StateChanged":
state = e["data"]["to"]
rid = e["data"]["folder"]
self._folder_state_changed(rid, state, 0)
elif eType in ("RemoteIndexUpdated"):
pass
elif eType == "DeviceConnected":
nid = e["data"]["id"]
self.emit("device-connected", nid)
elif eType == "DeviceDisconnected":
nid = e["data"]["id"]
self.emit("device-disconnected", nid)
elif eType == "DeviceDiscovered":
nid = e["data"]["device"]
addresses = e["data"]["addrs"]
self.emit("device-discovered", nid, addresses)
elif eType == "DevicePaused":
nid = e["data"]["device"]
self.emit("device-paused", nid)
elif eType == "DeviceResumed":
nid = e["data"]["device"]
self.emit("device-resumed", nid)
self._request_last_seen()
elif eType == "FolderRejected":
nid = e["data"]["device"]
rid = e["data"]["folder"]
label = e["data"]["folderLabel"] if "folderLabel" in e["data"] else None
self.emit("folder-rejected", nid, rid, label)
elif eType == "DeviceRejected":
nid = e["data"]["device"]
name = e["data"]["name"]
address = e["data"]["address"]
self.emit("device-rejected", nid, name, address)
elif eType == "FolderScanProgress":
rid = e["data"]["folder"]
total = float(e["data"]["total"])
if total > 0:
# ^^ just in case
status = float(e["data"]["current"]) / total
self.emit("folder-scan-progress", rid, status)
elif eType == "ItemStarted":
rid = e["data"]["folder"]
filename = e["data"]["item"]
t = parsetime(e["time"])
self.emit("item-started", rid, filename, t)
elif eType == "FolderCompletion":
self._syncthing_cb_completion(e["data"])
elif eType == "FolderSummary":
rid = e["data"]["folder"]
self._syncthing_cb_folder_data(e["data"]["summary"], rid)
elif eType == "FolderErrors":
rid = e["data"]["folder"]
self.emit("folder-error", rid, e["data"]["errors"])
elif eType == "ConfigSaved":
self.emit("config-saved")
elif eType == "ItemFinished":
rid = e["data"]["folder"]
if e["data"]["error"] is None:
filename = e["data"]["item"]
t = parsetime(e["time"])
self.emit("item-updated", rid, filename, t)
elif eType in ("ItemFinished", "DownloadProgress", "RelayStateChanged", "LocalIndexUpdated", "ListenAddressesChanged", "LoginAttempt"):
# Not handled
pass
else:
log.warning("Unhandled event type: %s", e)
# External stuff
def reconnect(self):
"""
Cancel all pending requests, throw away all data and (re)connect.
Should be called from glib loop
"""
self.close()
GLib.idle_add(self._request_config)
def reload_config(self, callback=None, error_callback=None):
"""
Reloads config from syncthing daemon.
Calling this will cause or may cause emiting following events
with reloaded data:
- folder-added
- device-added
- config-out-of-sync
"""
def reload_config_cb(config):
self._parse_dev_n_folders(config)
if callback is not None:
callback()
RESTRequest(self, "system/config/insync",
self._syncthing_cb_config_in_sync).start()
RESTRequest(self, "system/config", reload_config_cb,
error_callback).start()
def close(self):
"""
Terminates everything, cancel all pending requests, throws away
data.
Works like reconnect(), but without reconnecting.
"""
self._my_id = None
self._instance_id = None
self._connected = False
self._syncing_folders = set()
self._stopped_folders = set()
self._syncing_devices = set()
self._scanning_folders = set()
self._device_data = {}
self._folder_devices = {}
self._last_id = 0
self._last_seen = {}
self.cancel_all()
self._epoch += 1
def check_config(self):
"""
Check if configuration is in sync.
Should cause 'config-out-of-sync' event to be raised ASAP.
"""
RESTRequest(self, "system/config/insync",
self._syncthing_cb_config_in_sync).start()
def read_config(self, callback, error_callback=None, *calbackdata):
"""
Asynchronously reads last configuration version from daemon
(even if this version is not currently used). Calls
callback(config) with data decoded from json on success,
error_callback(exception) on failure
"""
RESTRequest(self, "system/config", callback,
error_callback, *calbackdata).start()
def write_config(self, config, callback, error_callback=None, *calbackdata):
"""
Asynchronously POSTs new configuration to daemon. Calls
callback() on success, error_callback(exception) on failure.
Should cause 'config-out-of-sync' event to be raised ASAP.
"""
def run_before(data, *a):
self.check_config()
callback(*calbackdata)
RESTPOSTRequest(self, "system/config", config, run_before,
error_callback, *calbackdata).start()
def read_stignore(self, folder_id, callback, error_callback=None, *calbackdata):
"""
Asynchronously reads .stignore data from from daemon.
Calls callback(text) with .stignore content on success,
error_callback(exception) on failure
"""
def r_filter(data, *a):
if "ignore" in data and data["ignore"] is not None:
callback("\n".join(data["ignore"]).strip(" \t\n"), *a)
else:
callback("", *a)
id_enc = urllib.parse.quote(folder_id.encode('utf-8'))
RESTRequest(self, "db/ignores?folder=%s" % (id_enc,),
r_filter, error_callback, *calbackdata).start()
def write_stignore(self, folder_id, text, callback, error_callback=None, *calbackdata):
"""
Asynchronously POSTs .stignore to daemon. Calls callback()
with on success, error_callback(exception) on failure.
"""
data = {'ignore': text.split("\n")}
id_enc = urllib.parse.quote(folder_id.encode('utf-8'))
RESTPOSTRequest(self, "db/ignores?folder=%s" % (id_enc,),
data, callback, error_callback, *calbackdata).start()
def restart(self):
"""
Asks daemon to restart. If successful, call will cause
'disconnected' event with Daemon.RESTART reason to be fired
"""
RESTPOSTRequest(self, "system/restart", {},
self._syncthing_cb_shutdown, None, Daemon.RESTART).start()
def shutdown(self):
"""
Asks daemon to shutdown. If successful, call will cause
'disconnected' event with Daemon.SHUTDOWN reason to be fired
"""
RESTPOSTRequest(self, "system/shutdown", {},
self._syncthing_cb_shutdown, None, Daemon.SHUTDOWN).start()
def syncing(self):
""" Returns true if any folder is being synchronized right now """
return len(self._syncing_folders) > 0
def get_api_key(self):
""" Returns API key used for communication with daemon. May return None """
return self._api_key
def get_min_version(self):
"""
Returns minimal syncthing daemon version that daemon instance
can handle.
"""
return MIN_VERSION
def get_syncing_list(self):
"""
Returns list of ids of foldersitories that are being
synchronized right now.
"""
return list(self._syncing_folders)
def get_my_id(self):
"""
Returns ID of device that is instance connected to.
May return None to indicate that ID is not yet known
"""
return self._my_id
def get_version(self):
"""
Returns daemon version or "unknown" if daemon version is not yet
known
"""
if self._my_id is None:
return "unknown"
device = self._get_device_data(self._my_id)
if "clientVersion" in device:
return device["clientVersion"]
return "unknown"
def get_webui_url(self):
""" Returns web ui url in http(s)://127.0.0.1:8080 format """
return "%s://%s" % (
"https" if self._tls else "http",
self._address
)
def get_address(self):
""" Returns tuple address on which daemon listens on. """
return self._address
def is_connected(self):
""" Returns True if daemon is known to be alive """
return self._connected
def pause(self, device_id):
""" Pauses synchronization with specified device """
RESTPOSTRequest(self, "system/pause?device=%s" % (device_id,),
{}, lambda *a: a, lambda *a: log.error(a), device_id).start()
def resume(self, device_id):
""" Resumes synchronization with specified device """
RESTPOSTRequest(self, "system/resume?device=%s" % (device_id,),
{}, lambda *a: a, lambda *a: log.error(a), device_id).start()
def rescan(self, folder_id, path=None):
""" Asks daemon to rescan entire folder or specified path """
if path is None:
id_enc = urllib.parse.quote(folder_id.encode('utf-8'))
RESTPOSTRequest(self, "db/scan?folder=%s" % (id_enc,), {},
lambda *a: a, lambda *a: log.error(a), folder_id).start()
else:
url = "db/scan?folder=%s&sub=%s" % (
urllib.parse.quote(folder_id.encode('utf-8')),
urllib.parse.quote(path.encode('utf-8'))
)
RESTPOSTRequest(self, url, {}, lambda *a: a,
lambda *a: log.error(a), folder_id).start()
def override(self, folder_id):
""" Asks daemon to override remote changes made in specified folder """
id_enc = urllib.parse.quote(folder_id.encode('utf-8'))
RESTPOSTRequest(self, "db/override?folder=%s" % (id_enc,), {},
lambda *a: a, lambda *a: log.error(a), folder_id).start()
def revert(self, folder_id):
""" Asks daemon to revert local changes made in specified folder """
id_enc = urllib.quote(folder_id.encode('utf-8'))
RESTPOSTRequest(self, "db/revert?folder=%s" % (id_enc,), {},
lambda *a: a, lambda *a: log.error(a), folder_id).start()
def request_events(self):
"""
No longer needed.
"""
def set_refresh_interval(self, i):
""" Sets interval used mainly by event querying timer """
self._refresh_interval = i
log.verbose("Set refresh interval to %s", i)
if __name__ == "__main__":
# Small thing for testing
from .tools import init_logging, set_logging_level
init_logging()
set_logging_level(True, True)
daemon = Daemon()
daemon.connect(
'connected', lambda *a: sys.stdout.write("*** connected ***\n"))
daemon.connect(
'disconnected', lambda *a: sys.stdout.write("*** disconnected ***\n"))
daemon.reconnect()
GLib.MainLoop().run()
|