syncstate.py 18 KB

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