syncstate.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. #
  2. # Copyright (C) by Klaas Freitag <freitag@owncloud.com>
  3. #
  4. # This program is the core of OwnCloud integration to Nautilus
  5. # It will be installed on /usr/share/nautilus-python/extensions/ with the paquet owncloud-client-nautilus
  6. # (https://github.com/owncloud/client/edit/master/shell_integration/nautilus/syncstate.py)
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful, but
  14. # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  15. # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  16. # for more details.
  17. import sys
  18. python3 = sys.version_info[0] >= 3
  19. import os
  20. import urllib
  21. if python3:
  22. import urllib.parse
  23. import socket
  24. import tempfile
  25. import time
  26. from gi.repository import GObject, Nautilus
  27. # Please do not touch the following line.
  28. # The reason is that we use a script to adopt this file for branding
  29. # by replacing this line with the branding app name. If the following
  30. # line is changed, the script can not match the pattern and fails.
  31. appname = 'Nextcloud'
  32. print("Initializing "+appname+"-client-nautilus extension")
  33. print("Using python version {}".format(sys.version_info))
  34. def get_local_path(url):
  35. if url[0:7] == 'file://':
  36. url = url[7:]
  37. unquote = urllib.parse.unquote if python3 else urllib.unquote
  38. return unquote(url)
  39. def get_runtime_dir():
  40. """Returns the value of $XDG_RUNTIME_DIR, a directory path.
  41. If the value is not set, returns the same default as in Qt5
  42. """
  43. try:
  44. return os.environ['XDG_RUNTIME_DIR']
  45. except KeyError:
  46. fallback = os.path.join(tempfile.gettempdir(), 'runtime-' + os.environ['USER'])
  47. return fallback
  48. class SocketConnect(GObject.GObject):
  49. def __init__(self):
  50. GObject.GObject.__init__(self)
  51. self.connected = False
  52. self.registered_paths = {}
  53. self._watch_id = 0
  54. self._sock = None
  55. self._listeners = [self._update_registered_paths, self._get_version]
  56. self._remainder = ''.encode() if python3 else ''
  57. self.protocolVersion = '1.0'
  58. self.nautilusVFSFile_table = {} # not needed in this object actually but shared
  59. # all over the other objects.
  60. # returns true when one should try again!
  61. if self._connectToSocketServer():
  62. GObject.timeout_add(5000, self._connectToSocketServer)
  63. def reconnect(self):
  64. self._sock.close()
  65. self.connected = False
  66. GObject.source_remove(self._watch_id)
  67. GObject.timeout_add(5000, self._connectToSocketServer)
  68. def sendCommand(self, cmd):
  69. # print("Server command: " + cmd)
  70. if self.connected:
  71. try:
  72. self._sock.send(cmd.encode() if python3 else cmd)
  73. except:
  74. print("Sending failed.")
  75. self.reconnect()
  76. else:
  77. print("Cannot send, not connected!")
  78. def addListener(self, listener):
  79. self._listeners.append(listener)
  80. def _connectToSocketServer(self):
  81. try:
  82. self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  83. sock_file = os.path.join(get_runtime_dir(), appname, "socket")
  84. try:
  85. self._sock.connect(sock_file) # fails if sock_file doesn't exist
  86. self.connected = True
  87. self._watch_id = GObject.io_add_watch(self._sock, GObject.IO_IN, self._handle_notify)
  88. self.sendCommand('VERSION:\n')
  89. self.sendCommand('GET_STRINGS:\n')
  90. return False # Don't run again
  91. except Exception as e:
  92. print("Could not connect to unix socket " + sock_file + ". " + str(e))
  93. except Exception as e: # Bad habbit
  94. print("Connect could not be established, try again later.")
  95. self._sock.close()
  96. return True # Run again, if enabled via timeout_add()
  97. # Reads data that becomes available.
  98. # New responses can be accessed with get_available_responses().
  99. # Returns false if no data was received within timeout
  100. def read_socket_data_with_timeout(self, timeout):
  101. self._sock.settimeout(timeout)
  102. try:
  103. self._remainder += self._sock.recv(1024)
  104. except socket.timeout:
  105. return False
  106. else:
  107. return True
  108. finally:
  109. self._sock.settimeout(None)
  110. # Parses response lines out of collected data, returns list of strings
  111. def get_available_responses(self):
  112. end = self._remainder.rfind(b'\n')
  113. if end == -1:
  114. return []
  115. data = self._remainder[:end]
  116. self._remainder = self._remainder[end+1:]
  117. data = data.decode() if python3 else data
  118. return data.split('\n')
  119. # Notify is the raw answer from the socket
  120. def _handle_notify(self, source, condition):
  121. # Blocking is ok since we're notified of available data
  122. self._remainder += self._sock.recv(1024)
  123. if len(self._remainder) == 0:
  124. return False
  125. for line in self.get_available_responses():
  126. self.handle_server_response(line)
  127. return True # Run again
  128. def handle_server_response(self, line):
  129. # print("Server response: " + line)
  130. parts = line.split(':')
  131. action = parts[0]
  132. args = parts[1:]
  133. for listener in self._listeners:
  134. listener(action, args)
  135. def _update_registered_paths(self, action, args):
  136. if action == 'REGISTER_PATH':
  137. self.registered_paths[args[0]] = 1
  138. elif action == 'UNREGISTER_PATH':
  139. del self.registered_paths[args[0]]
  140. # Check if there are no paths left. If so, its usual
  141. # that mirall went away. Try reconnecting.
  142. if not self.registered_paths:
  143. self.reconnect()
  144. def _get_version(self, action, args):
  145. if action == 'VERSION':
  146. self.protocolVersion = args[1]
  147. socketConnect = SocketConnect()
  148. class MenuExtension(GObject.GObject, Nautilus.MenuProvider):
  149. def __init__(self):
  150. GObject.GObject.__init__(self)
  151. self.strings = {}
  152. socketConnect.addListener(self.handle_commands)
  153. def handle_commands(self, action, args):
  154. if action == 'STRING':
  155. self.strings[args[0]] = ':'.join(args[1:])
  156. def check_registered_paths(self, filename):
  157. topLevelFolder = False
  158. internalFile = False
  159. for reg_path in socketConnect.registered_paths:
  160. if filename == reg_path:
  161. topLevelFolder = True
  162. break
  163. if filename.startswith(reg_path):
  164. internalFile = True
  165. # you can't have a registered path below another so it is save to break here
  166. break
  167. return (topLevelFolder, internalFile)
  168. def get_file_items(self, window, files):
  169. # Show the menu extension to share a file or folder
  170. # Get usable file paths from the uris
  171. all_internal_files = True
  172. for i, file_uri in enumerate(files):
  173. filename = get_local_path(file_uri.get_uri())
  174. # Check if its a folder (ends with an /), if yes add a "/"
  175. # otherwise it will not find the entry in the table
  176. isDir = os.path.isdir(filename + os.sep)
  177. if isDir:
  178. filename += os.sep
  179. # Check if toplevel folder, we need to ignore those as they cannot be shared
  180. topLevelFolder, internalFile = self.check_registered_paths(filename)
  181. if not internalFile:
  182. all_internal_files = False
  183. files[i] = filename
  184. # Don't show a context menu if some selected files aren't in a sync folder
  185. if not all_internal_files:
  186. return []
  187. if socketConnect.protocolVersion >= '1.1': # lexicographic!
  188. return self.ask_for_menu_items(files)
  189. else:
  190. return self.legacy_menu_items(files)
  191. def ask_for_menu_items(self, files):
  192. record_separator = '\x1e'
  193. filesstring = record_separator.join(files)
  194. socketConnect.sendCommand(u'GET_MENU_ITEMS:{}\n'.format(filesstring))
  195. done = False
  196. start = time.time()
  197. timeout = 0.1 # 100ms
  198. menu_items = []
  199. while not done:
  200. dt = time.time() - start
  201. if dt >= timeout:
  202. break
  203. if not socketConnect.read_socket_data_with_timeout(timeout - dt):
  204. break
  205. for line in socketConnect.get_available_responses():
  206. # Process lines we don't care about
  207. if done or not (line.startswith('GET_MENU_ITEMS:') or line.startswith('MENU_ITEM:')):
  208. socketConnect.handle_server_response(line)
  209. continue
  210. if line == 'GET_MENU_ITEMS:END':
  211. done = True
  212. # don't break - we'd discard other responses
  213. if line.startswith('MENU_ITEM:'):
  214. args = line.split(':')
  215. if len(args) < 4:
  216. continue
  217. menu_items.append([args[1], 'd' not in args[2], ':'.join(args[3:])])
  218. if not done:
  219. return self.legacy_menu_items(files)
  220. if len(menu_items) == 0:
  221. return []
  222. # Set up the 'ownCloud...' submenu
  223. item_owncloud = Nautilus.MenuItem(
  224. name='IntegrationMenu', label=self.strings.get('CONTEXT_MENU_TITLE', appname))
  225. menu = Nautilus.Menu()
  226. item_owncloud.set_submenu(menu)
  227. for action, enabled, label in menu_items:
  228. item = Nautilus.MenuItem(name=action, label=label, sensitive=enabled)
  229. item.connect("activate", self.context_menu_action, action, filesstring)
  230. menu.append_item(item)
  231. return [item_owncloud]
  232. def legacy_menu_items(self, files):
  233. # No legacy menu for a selection of several files
  234. if len(files) != 1:
  235. return []
  236. filename = files[0]
  237. entry = socketConnect.nautilusVFSFile_table.get(filename)
  238. if not entry:
  239. return []
  240. # Currently 'sharable' also controls access to private link actions,
  241. # and we definitely don't want to show them for IGNORED.
  242. shareable = False
  243. state = entry['state']
  244. state_ok = state.startswith('OK')
  245. state_sync = state.startswith('SYNC')
  246. if state_ok:
  247. shareable = True
  248. elif state_sync and isDir:
  249. # some file below is OK or SYNC
  250. for key, value in socketConnect.nautilusVFSFile_table.items():
  251. if key != filename and key.startswith(filename):
  252. state = value['state']
  253. if state.startswith('OK') or state.startswith('SYNC'):
  254. shareable = True
  255. break
  256. if not shareable:
  257. return []
  258. # Set up the 'ownCloud...' submenu
  259. item_owncloud = Nautilus.MenuItem(
  260. name='IntegrationMenu', label=self.strings.get('CONTEXT_MENU_TITLE', appname))
  261. menu = Nautilus.Menu()
  262. item_owncloud.set_submenu(menu)
  263. # Add share menu option
  264. item = Nautilus.MenuItem(
  265. name='NautilusPython::ShareItem',
  266. label=self.strings.get('SHARE_MENU_TITLE', 'Share...'))
  267. item.connect("activate", self.context_menu_action, 'SHARE', filename)
  268. menu.append_item(item)
  269. # Add permalink menu options, but hide these options for older clients
  270. # that don't have these actions.
  271. if 'COPY_PRIVATE_LINK_MENU_TITLE' in self.strings:
  272. item_copyprivatelink = Nautilus.MenuItem(
  273. name='CopyPrivateLink', label=self.strings.get('COPY_PRIVATE_LINK_MENU_TITLE', 'Copy private link to clipboard'))
  274. item_copyprivatelink.connect("activate", self.context_menu_action, 'COPY_PRIVATE_LINK', filename)
  275. menu.append_item(item_copyprivatelink)
  276. if 'EMAIL_PRIVATE_LINK_MENU_TITLE' in self.strings:
  277. item_emailprivatelink = Nautilus.MenuItem(
  278. name='EmailPrivateLink', label=self.strings.get('EMAIL_PRIVATE_LINK_MENU_TITLE', 'Send private link by email...'))
  279. item_emailprivatelink.connect("activate", self.context_menu_action, 'EMAIL_PRIVATE_LINK', filename)
  280. menu.append_item(item_emailprivatelink)
  281. return [item_owncloud]
  282. def context_menu_action(self, menu, action, filename):
  283. # print("Context menu: " + action + ' ' + filename)
  284. socketConnect.sendCommand(action + ":" + filename + "\n")
  285. class SyncStateExtension(GObject.GObject, Nautilus.InfoProvider):
  286. def __init__(self):
  287. GObject.GObject.__init__(self)
  288. socketConnect.nautilusVFSFile_table = {}
  289. socketConnect.addListener(self.handle_commands)
  290. def find_item_for_file(self, path):
  291. if path in socketConnect.nautilusVFSFile_table:
  292. return socketConnect.nautilusVFSFile_table[path]
  293. else:
  294. return None
  295. def askForOverlay(self, file):
  296. # print("Asking for overlay for "+file) # For debug only
  297. if os.path.isdir(file):
  298. folderStatus = socketConnect.sendCommand("RETRIEVE_FOLDER_STATUS:"+file+"\n");
  299. if os.path.isfile(file):
  300. fileStatus = socketConnect.sendCommand("RETRIEVE_FILE_STATUS:"+file+"\n");
  301. def invalidate_items_underneath(self, path):
  302. update_items = []
  303. if not socketConnect.nautilusVFSFile_table:
  304. self.askForOverlay(path)
  305. else:
  306. for p in socketConnect.nautilusVFSFile_table:
  307. if p == path or p.startswith(path):
  308. item = socketConnect.nautilusVFSFile_table[p]['item']
  309. update_items.append(p)
  310. for path1 in update_items:
  311. socketConnect.nautilusVFSFile_table[path1]['item'].invalidate_extension_info()
  312. # Handles a single line of server response and sets the emblem
  313. def handle_commands(self, action, args):
  314. # file = args[0] # For debug only
  315. # print("Action for " + file + ": " + args[0]) # For debug only
  316. if action == 'STATUS':
  317. newState = args[0]
  318. filename = ':'.join(args[1:])
  319. itemStore = self.find_item_for_file(filename)
  320. if itemStore:
  321. if( not itemStore['state'] or newState != itemStore['state'] ):
  322. item = itemStore['item']
  323. # print("Setting emblem on " + filename + "<>" + emblem + "<>") # For debug only
  324. # If an emblem is already set for this item, we need to
  325. # clear the existing extension info before setting a new one.
  326. #
  327. # That will also trigger a new call to
  328. # update_file_info for this item! That's why we set
  329. # skipNextUpdate to True: we don't want to pull the
  330. # current data from the client after getting a push
  331. # notification.
  332. invalidate = itemStore['state'] != None
  333. if invalidate:
  334. item.invalidate_extension_info()
  335. self.set_emblem(item, newState)
  336. socketConnect.nautilusVFSFile_table[filename] = {
  337. 'item': item,
  338. 'state': newState,
  339. 'skipNextUpdate': invalidate }
  340. elif action == 'UPDATE_VIEW':
  341. # Search all items underneath this path and invalidate them
  342. if args[0] in socketConnect.registered_paths:
  343. self.invalidate_items_underneath(args[0])
  344. elif action == 'REGISTER_PATH':
  345. self.invalidate_items_underneath(args[0])
  346. elif action == 'UNREGISTER_PATH':
  347. self.invalidate_items_underneath(args[0])
  348. def set_emblem(self, item, state):
  349. Emblems = { 'OK' : appname +'_ok',
  350. 'SYNC' : appname +'_sync',
  351. 'NEW' : appname +'_sync',
  352. 'IGNORE' : appname +'_warn',
  353. 'ERROR' : appname +'_error',
  354. 'OK+SWM' : appname +'_ok_shared',
  355. 'SYNC+SWM' : appname +'_sync_shared',
  356. 'NEW+SWM' : appname +'_sync_shared',
  357. 'IGNORE+SWM': appname +'_warn_shared',
  358. 'ERROR+SWM' : appname +'_error_shared',
  359. 'NOP' : ''
  360. }
  361. emblem = 'NOP' # Show nothing if no emblem is defined.
  362. if state in Emblems:
  363. emblem = Emblems[state]
  364. item.add_emblem(emblem)
  365. def update_file_info(self, item):
  366. if item.get_uri_scheme() != 'file':
  367. return
  368. filename = get_local_path(item.get_uri())
  369. if item.is_directory():
  370. filename += os.sep
  371. inScope = False
  372. for reg_path in socketConnect.registered_paths:
  373. if filename.startswith(reg_path):
  374. inScope = True
  375. break
  376. if not inScope:
  377. return
  378. # Ask for the current state from the client -- unless this update was
  379. # triggered by receiving a STATUS message from the client in the first
  380. # place.
  381. itemStore = self.find_item_for_file(filename)
  382. if itemStore and itemStore['skipNextUpdate'] and itemStore['state']:
  383. itemStore['skipNextUpdate'] = False
  384. itemStore['item'] = item
  385. self.set_emblem(item, itemStore['state'])
  386. else:
  387. socketConnect.nautilusVFSFile_table[filename] = {
  388. 'item': item,
  389. 'state': None,
  390. 'skipNextUpdate': False }
  391. # item.add_string_attribute('share_state', "share state") # ?
  392. self.askForOverlay(filename)