1
0
mirror of https://github.com/chylex/Nextcloud-Desktop.git synced 2026-04-05 05:34:18 +02:00

Compare commits

..

1 Commits

Author SHA1 Message Date
Markus Goetz
339ecfae0c VERSION.cmake: 2.4.0 alpha1 2017-10-05 17:43:32 +02:00
141 changed files with 11264 additions and 15795 deletions

View File

@@ -199,7 +199,7 @@ if(BUILD_CLIENT)
endif() endif()
endif() endif()
find_package(ZLIB REQUIRED) find_package(ZLIB)
endif() endif()
if (NOT DEFINED APPLICATION_ICON_NAME) if (NOT DEFINED APPLICATION_ICON_NAME)
@@ -243,7 +243,6 @@ set(WITH_TESTING ${UNIT_TESTING})
if(BUILD_CLIENT) if(BUILD_CLIENT)
add_subdirectory(src) add_subdirectory(src)
if(NOT BUILD_LIBRARIES_ONLY) if(NOT BUILD_LIBRARIES_ONLY)
add_subdirectory(man)
add_subdirectory(doc) add_subdirectory(doc)
add_subdirectory(doc/dev) add_subdirectory(doc/dev)
if(IS_DIRECTORY ${CMAKE_SOURCE_DIR}/admin) if(IS_DIRECTORY ${CMAKE_SOURCE_DIR}/admin)

View File

@@ -1,105 +1,75 @@
ChangeLog ChangeLog
========= =========
version 2.4.0 (2017-12-XX) version 2.4.0 (2017-1X-XX)
* If you're using 2.4.0 alpha1, please upgrade as the alpha1 had an issue with hidden files! * OAuth2 authentication support by opening external browser
* OAuth2 authentication support by opening external browser (#5668) * Sync Issues: More functional error view including filters and conflicts (#5516)
* Shibboleth: Change to use OAuth2 if supported (#6198)
* Sharing: Add support for multiple public link shares (#5655) * Sharing: Add support for multiple public link shares (#5655)
* Sharing: Add option to copy/email private links (#5023, #5627) * Sharing: Add option to copy/email private links (#5627, #5023)
* Sharing: Add option "show file listing" (#5837) * Sharing: Add option "show file listing" (#5837)
* Sharing: Show warning that links are public (#5747) * Sharing: Show warning that links are public
* Sharing: Sharing dialog redesign: multiple share links support (#5695) * Sharing: Many UI improvements
* Sharing: Make "can edit" partially checked sometimes (#5642) * Sharing: Make "can edit" partially checked sometimes (#5642)
* Sharing: Trigger a sync for folder affected by a change of sharing (#6098)
* Wizard: Never propose an existing folder for syncing (#5597) * Wizard: Never propose an existing folder for syncing (#5597)
* Wizard: Don't show last page anymore, go to settings directly (#5726) * Wizard: Don't show last page anymore, go to settings directly (#5726)
* Wizard: Handle url-shortener redirects (#5954) * Wizard: Handle url-shortener redirects #5954
* Wizard: Resolve url/ redirects only if url/status.php not found (#5954) * Gui: Display the user server avatar
* Wizard: Add explanation text when server error is shown (#6157)
* Wizard: Update the window size on high dpi screen (#6156)
* Wizard: Don't report confusing error message (#6116)
* Gui: Display the user server avatar (#5482)
* Gui: Use display name of user, not internal name
* Server URL: Update configuration in case of permanent redirection (#5972) * Server URL: Update configuration in case of permanent redirection (#5972)
* Gui: Allow to add multiple sync folder connection of the same folder (#6032) * Gui: Allow to add multiple sync folder connection of the same folder
* Tray Menu: More detailed status messages
* Tray Menu: Shibboleth: raise the browser when clicking on the tray (#6105)
* Activity: Link errors from the account tab, allow filtering by account/folder (#5861)
* Activity: Present conflicts more prominently (#5894)
* Activity: Allow sorting the columns in issues and protocol tabs (#6093, #6086)
* Selective Sync: Open sub folder context menu (#5596) * Selective Sync: Open sub folder context menu (#5596)
* Selective Sync: Skip excluded folders when reading db (#5772) * Selective Sync: Skip excluded folders when reading db
* Selective Sync: Remove local files of unselected folder despite other modified files (#5783) * Selective Sync: Remove local files of unselected folder despite other modified files (#5783)
* Excludes: Remove .htaccess form list of excluded files (#5701) * Excludes: remove .htaccess form list of excluded files
* Excludes: Hardcode desktop.ini * Excludes: Hardcode desktop.ini
* Excludes: Allow escaping "#" (#6012) * Excludes: Allow escaping "#" (#6012)
* Excludes: Use faster matching via QRegularExpression (#6063) * Excludes: Use faster matching via QRegularExpression
* Discovery: Increase the MAX_DEPTH and show deep folders as ignored (#1067) * Discovery: Increase the MAX_DEPTH and show deep folders as ignored
* Discovery: General speed improvements * Discovery: General speed improvements
* Downloads: Remove empty temporary if disk space full (#5746) * Downloads: Remove empty temporary if disk space full (#5746)
* Downloads: Read Content-MD5 header for object store setups * Downloads: Re-trigger folder discovery on 404
* Checksums: Add global disable environment variable (#5017) * Quota: PropagateUpload: Model of remote quota, avoid some uploads (#5537)
* Quota: PropagateUpload: Model of remote quota, avoid some uploads (#5537) * When creating explorer favorite use more specific windows functions (#5690)
* Create favorite also in folder wizard (#455) * Create favorite also in folder wizard (#455)
* Windows: Use the application icon for the Windows 8 sidebar favorite (#2446, #5690) * Windows: Use the application icon for the Windows 8 sidebar favorite (#2446)
* macOS: Finder sidebar icon (#296) * macOS: Finder sidebar icon (#296)
* Overlay Icons: Consider also the "shared by me" as shared (#4788) * Overlay Icons: Consider also the "shared by me" as shared (#4788)
* Overlay Icons: Update right after sharing (#6115)
* Overlay Icons: Fix different case paths not matching (#5257) * Overlay Icons: Fix different case paths not matching (#5257)
* Overlay Icons: Detect changes in the shared flag (#6098)
* Windows Overlay Icons: Potential hang fixes * Windows Overlay Icons: Potential hang fixes
* Linux Overlay Icons: fix branded nemo and caja shell integration (#5966) * Linux Overlay Icons: fix branded nemo and caja shell integration (#5966)
* Credentials: Fix behavior for bad password (#5989) * Http credentials: Fix behavior for bad password (#5989)
* Credentials: Don't create empty client cert keychain entries (#5752) * Credentials: Use per-account keychain entries (#5830)
* Credentials: Namespace windows cred keys (#6125)
* Credentials: Use per-account keychain entries (#5830, #6126)
* AccountSettings: Triggering log in re-ask about previously rejected certificates (#5819) * AccountSettings: Triggering log in re-ask about previously rejected certificates (#5819)
* owncloudcmd: Added bandwidth limit parameter (#5707) * Added owncloudcmd bandwidth limit parameter (#5707)
* owncloudcmd: Fix timestamps, Fix --logdebug
* AccountSettings: Sync with clean discovery on Ctrl-F6 (#5666) * AccountSettings: Sync with clean discovery on Ctrl-F6 (#5666)
* Sync: Dynamic sizing of chunks in chunked uploads for improved big file upload performance (#5852) * Sync: Dynamic sizing of chunks in chunked uploads for improved big file upload performance
* Sync: Introduce overall errors that are not tied to a file (#5746) * Sync: Introduce overall errors that are not tied to a file (#5746)
* Sync: Better messaging for 507 Insufficient Storage (#5537) * Sync: Better messaging for 507 Insufficient Storage (#5537)
* Sync: Create conflicts by comparing the hash of files with identical mtime/size (#5589) * Sync: Create conflicts by comparing the hash of files with identical mtime/size (#5589)
* Sync: Avoid downloads by comparing the hash of files with identical mtime/size (#6153)
* Sync: Upload conflict files if OWNCLOUD_UPLOAD_CONFLICT_FILES environment variable is set (#6038)
* Sync: Blacklist: Don't let errors become warnings (#5516) * Sync: Blacklist: Don't let errors become warnings (#5516)
* Sync: Check etag again after active sync (#4116) * Sync: Check etag again after active sync (#4116)
* Sync: Rename handling fixes: duplicate file ids (#6096)
* Sync: Rename handling fixes: File size must be equal
* Sync: Rename handling: Fix duplicate files on abort/resume sync (#5949)
* Sync: Add capability for invalid filename regexes (#6092)
* SyncJournalDB: Fall back to DELETE journal mode if WAL mode does not seem to work (#5723) * SyncJournalDB: Fall back to DELETE journal mode if WAL mode does not seem to work (#5723)
* SyncJournalDB: Don't crash if the db file is readonly (#6050)
* SyncJournalDB: DB close error is not fatal
* Fix at least one memory leak * Fix at least one memory leak
* Documentation improvements * Documentation improvements
* Logging improvements (With Qt logging categories) (#5671) * Logging improvements (with Qt logging categories), new --logdebug parameter
* Logging filtering per account (#5672)
* Crash fixes * Crash fixes
* Test improvements * Test improvements
* Small UI layout fixes * Small UI layout fixes
* Maintenance Mode: Detect maintenance mode (#4485) * Maintenance Mode: Detect maintenance mode (#4485)
* Maintenance Mode: Add a 1 to 5 min reconnection delay (#5872) * Maintenance Mode: Add a 1 to 5 min reconnection delay (#5872)
* HTTP: Send a unique X-Request-ID with each request (#5853) * HTTP: Send a unique X-Request-ID with each request (#5853)
* HTTP: Support HTTP2 when built and running with Qt 5.9.x (Official packages still on Qt 5.6.x) (#5659) * HTTP: Support HTTP2 when built and running with Qt 5.9.x (Official packages still on Qt 5.6.x)
* owncloudcmd: Don't start if connection or auth fails (#5692) * owncloudcmd: Don't start if connection or auth fails (#5692)
* csync: Switch build from C to C++ (#6033) * csync: Switch build from C to C++
* csync: Refactor a lot to use common data structures to save memory and memory copying * csync: Refactor a lot to use common data structures to save memory and memory copying
* csync: Switch some data structures to Qt data structures * csync: Switch some data structures to Qt data structures
* csync: Switch to using upper layer SyncJournalDB (#6087) * csync: Switch to using upper layer SyncJournalDB
* Switch 3rdparty/json usage to Qt5's QJson (#5710) * Switch 3rdparty/json usage to Qt5's QJson (#5710)
* OpenSSL: Don't require directly, only via Qt (#5833) * OpenSSL: Don't require directly, only via Qt
* Remove iconv dependency, use Qt for file system locale encoding/decoding (emoji filename support on macOS) (#5875) * Remove iconv dependency, use Qt for file system locale encoding/decoding (emoji filename support on macOS)
* Compilation: Remove Qt 4 code (#6025, #5702, #5505) * Compilation: Remove Qt 4 code
* Harmonize source code style with clang-format (#5732) * Harmonize source code style with clang-format
* Switch over to Qt 5 function pointer signal/slot syntax (#6041) * Switch over to Qt 5 function pointer signal/slot syntax
* Updater: Rudimentary support for beta channel (#6048) * Updater: Rudimentary support for beta channel
version 2.3.4 (2017-11-02)
* Checksums: Use addData function to avoid endless loop CPU load issues with Office files
* Packaging: Require ZLIB
version 2.3.3 (2017-08-29) version 2.3.3 (2017-08-29)
* Chunking NG: Don't use old chunking on new DAV endpoint (#5855) * Chunking NG: Don't use old chunking on new DAV endpoint (#5855)

View File

@@ -5,7 +5,7 @@ set( MIRALL_VERSION_YEAR 2017 )
set( MIRALL_SOVERSION 0 ) set( MIRALL_SOVERSION 0 )
if ( NOT DEFINED MIRALL_VERSION_SUFFIX ) if ( NOT DEFINED MIRALL_VERSION_SUFFIX )
set( MIRALL_VERSION_SUFFIX "rc1") #e.g. beta1, beta2, rc1 set( MIRALL_VERSION_SUFFIX "alpha1") #e.g. beta1, beta2, rc1
endif( NOT DEFINED MIRALL_VERSION_SUFFIX ) endif( NOT DEFINED MIRALL_VERSION_SUFFIX )
if( NOT DEFINED MIRALL_VERSION_BUILD ) if( NOT DEFINED MIRALL_VERSION_BUILD )

View File

@@ -3,7 +3,7 @@ StrCpy $MUI_FINISHPAGE_SHOWREADME_TEXT_STRING "Vis versjonsmerknader"
StrCpy $ConfirmEndProcess_MESSAGEBOX_TEXT "Fant ${APPLICATION_EXECUTABLE}-prosess(er) som må stoppes.$\nVil du at installasjonsprogrammet skal stoppe dem for deg?" StrCpy $ConfirmEndProcess_MESSAGEBOX_TEXT "Fant ${APPLICATION_EXECUTABLE}-prosess(er) som må stoppes.$\nVil du at installasjonsprogrammet skal stoppe dem for deg?"
StrCpy $ConfirmEndProcess_KILLING_PROCESSES_TEXT "Terminerer ${APPLICATION_EXECUTABLE}-prosesser." StrCpy $ConfirmEndProcess_KILLING_PROCESSES_TEXT "Terminerer ${APPLICATION_EXECUTABLE}-prosesser."
StrCpy $ConfirmEndProcess_KILL_NOT_FOUND_TEXT "Fant ikke prosess som skulle termineres!" StrCpy $ConfirmEndProcess_KILL_NOT_FOUND_TEXT "Fant ikke prosess som skulle termineres!"
StrCpy $PageReinstall_NEW_Field_1 "En eldre versjon av ${APPLICATION_NAME} er installert på systemet ditt. Det anbefales at du avinstallerer den versjonen før installering av ny versjon. Velg hva du vil gjøre og klikk Neste for å fortsette." StrCpy $PageReinstall_NEW_Field_1 "En eldre versjon av ${APPLICATION_NAME} er installert på systemet ditt. Det anbefales at du avnistallerer den versjonen før installering av ny versjon. Velg hva du vil gjøre og klikk Neste for å fortsette."
StrCpy $PageReinstall_NEW_Field_2 "Avinstaller før installering" StrCpy $PageReinstall_NEW_Field_2 "Avinstaller før installering"
StrCpy $PageReinstall_NEW_Field_3 "Ikke avinstaller" StrCpy $PageReinstall_NEW_Field_3 "Ikke avinstaller"
StrCpy $PageReinstall_NEW_MUI_HEADER_TEXT_TITLE "Allerede installert" StrCpy $PageReinstall_NEW_MUI_HEADER_TEXT_TITLE "Allerede installert"

View File

@@ -1,9 +1,9 @@
# Auto-generated - do not modify # Auto-generated - do not modify
StrCpy $MUI_FINISHPAGE_SHOWREADME_TEXT_STRING "Mostrar las notas de la versión" StrCpy $MUI_FINISHPAGE_SHOWREADME_TEXT_STRING "Mostrar las notas de la versión"
StrCpy $ConfirmEndProcess_MESSAGEBOX_TEXT "El/los proceso(s) ${APPLICATION_EXECUTABLE} debe(n) ser detenido(s).$\n¿Quiere que el instalador lo haga por usted?" StrCpy $ConfirmEndProcess_MESSAGEBOX_TEXT "El/los proceso/s ${APPLICATION_EXECUTABLE} debe/n ser detenidos.$\n¿Quiere que el instalador lo haga por usted?"
StrCpy $ConfirmEndProcess_KILLING_PROCESSES_TEXT "Deteniendo el/los proceso(s) ${APPLICATION_EXECUTABLE}." StrCpy $ConfirmEndProcess_KILLING_PROCESSES_TEXT "Deteniendo el/los proceso/s ${APPLICATION_EXECUTABLE}."
StrCpy $ConfirmEndProcess_KILL_NOT_FOUND_TEXT "¡Proceso a finalizar no encontrado!" StrCpy $ConfirmEndProcess_KILL_NOT_FOUND_TEXT "¡Proceso a finalizar no encontrado!"
StrCpy $PageReinstall_NEW_Field_1 "Una versión anterior de ${APPLICATION_NAME} se encuentra instalada en el sistema. Se recomienda desinstalar la versión actual antes de instalar la nueva. Seleccione la operacion deseada y haga click en Siguiente para continuar." StrCpy $PageReinstall_NEW_Field_1 "Una versión anterior de ${APPLICATION_NAME} se encuentra instalada en el sistema. Se recomienda de instalar la versión actual antes de instalar la nueva. Seleccione la operacion deseada y haga click en Siguiente para continuar."
StrCpy $PageReinstall_NEW_Field_2 "Desinstalar antes de instalar" StrCpy $PageReinstall_NEW_Field_2 "Desinstalar antes de instalar"
StrCpy $PageReinstall_NEW_Field_3 "No desinstalar" StrCpy $PageReinstall_NEW_Field_3 "No desinstalar"
StrCpy $PageReinstall_NEW_MUI_HEADER_TEXT_TITLE "Ya está instalado" StrCpy $PageReinstall_NEW_MUI_HEADER_TEXT_TITLE "Ya está instalado"
@@ -17,13 +17,13 @@ StrCpy $PageReinstall_SAME_MUI_HEADER_TEXT_SUBTITLE "Elija la opcion de mantenim
StrCpy $SEC_APPLICATION_DETAILS "Instalando ${APPLICATION_NAME} esenciales." StrCpy $SEC_APPLICATION_DETAILS "Instalando ${APPLICATION_NAME} esenciales."
StrCpy $OPTION_SECTION_SC_SHELL_EXT_SECTION "Integración para Windows Explorer" StrCpy $OPTION_SECTION_SC_SHELL_EXT_SECTION "Integración para Windows Explorer"
StrCpy $OPTION_SECTION_SC_SHELL_EXT_DetailPrint "Instalando la integración para Windows Explorer" StrCpy $OPTION_SECTION_SC_SHELL_EXT_DetailPrint "Instalando la integración para Windows Explorer"
StrCpy $OPTION_SECTION_SC_START_MENU_SECTION "Acceso directo al programa en Menú de Inicio" StrCpy $OPTION_SECTION_SC_START_MENU_SECTION "Acceso directo al programa Menú de Inicio"
StrCpy $OPTION_SECTION_SC_START_MENU_DetailPrint "Añadiendo accesos directos para ${APPLICATION_NAME} en el Menú de Inicio." StrCpy $OPTION_SECTION_SC_START_MENU_DetailPrint "Añadiendo accesos directos para ${APPLICATION_NAME} en el Menú de Inicio."
StrCpy $OPTION_SECTION_SC_DESKTOP_SECTION "Acceso directo de Escritorio" StrCpy $OPTION_SECTION_SC_DESKTOP_SECTION "Acceso directo de Escritorio"
StrCpy $OPTION_SECTION_SC_DESKTOP_DetailPrint "Creando accesos directos de escritorio" StrCpy $OPTION_SECTION_SC_DESKTOP_DetailPrint "Creando accesos directos de escritorio"
StrCpy $OPTION_SECTION_SC_QUICK_LAUNCH_SECTION "Atajo de acceso rápido" StrCpy $OPTION_SECTION_SC_QUICK_LAUNCH_SECTION "Atajo de accceso rápido"
StrCpy $OPTION_SECTION_SC_QUICK_LAUNCH_DetailPrint "Creando un Acceso Directo al Lanzador Rápido" StrCpy $OPTION_SECTION_SC_QUICK_LAUNCH_DetailPrint "Creando un Acceso Directo al Lanzador Rápido"
StrCpy $OPTION_SECTION_SC_APPLICATION_Desc "${APPLICATION_NAME} esenciales." StrCpy $OPTION_SECTION_SC_APPLICATION_Desc "${APPLICATION_NAME} esencial."
StrCpy $OPTION_SECTION_SC_START_MENU_Desc "Acceso Directo de ${APPLICATION_NAME}" StrCpy $OPTION_SECTION_SC_START_MENU_Desc "Acceso Directo de ${APPLICATION_NAME}"
StrCpy $OPTION_SECTION_SC_DESKTOP_Desc "Acceso Directo de Escritorio para ${APPLICATION_NAME}" StrCpy $OPTION_SECTION_SC_DESKTOP_Desc "Acceso Directo de Escritorio para ${APPLICATION_NAME}"
StrCpy $OPTION_SECTION_SC_QUICK_LAUNCH_Desc "Lanzador Rápido de Accesos Director para ${APPLICATION_NAME}." StrCpy $OPTION_SECTION_SC_QUICK_LAUNCH_Desc "Lanzador Rápido de Accesos Director para ${APPLICATION_NAME}."

View File

@@ -4,6 +4,7 @@ if(SPHINX_FOUND)
set(SPHINX_CACHE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_doctrees") set(SPHINX_CACHE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_doctrees")
# HTML output directory # HTML output directory
set(SPHINX_HTML_DIR "${CMAKE_CURRENT_BINARY_DIR}/html") set(SPHINX_HTML_DIR "${CMAKE_CURRENT_BINARY_DIR}/html")
set(SPHINX_MAN_DIR "${CMAKE_CURRENT_BINARY_DIR}/man1")
set(SPHINX_PDF_DIR "${CMAKE_CURRENT_BINARY_DIR}/latex") set(SPHINX_PDF_DIR "${CMAKE_CURRENT_BINARY_DIR}/latex")
set(SPHINX_QCH_DIR "${CMAKE_CURRENT_BINARY_DIR}/qthelp") set(SPHINX_QCH_DIR "${CMAKE_CURRENT_BINARY_DIR}/qthelp")
set(SPHINX_HTMLHELP_DIR "${CMAKE_CURRENT_BINARY_DIR}/htmlhelp") set(SPHINX_HTMLHELP_DIR "${CMAKE_CURRENT_BINARY_DIR}/htmlhelp")
@@ -16,6 +17,8 @@ if(SPHINX_FOUND)
install(DIRECTORY ${SPHINX_PDF_DIR} DESTINATION ${APPLICATION_DOC_DIR} OPTIONAL) install(DIRECTORY ${SPHINX_PDF_DIR} DESTINATION ${APPLICATION_DOC_DIR} OPTIONAL)
install(DIRECTORY ${SPHINX_QCH_DIR} DESTINATION ${APPLICATION_DOC_DIR} OPTIONAL) install(DIRECTORY ${SPHINX_QCH_DIR} DESTINATION ${APPLICATION_DOC_DIR} OPTIONAL)
install(DIRECTORY ${SPHINX_MAN_DIR} DESTINATION ${CMAKE_INSTALL_MANDIR} OPTIONAL)
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/conf.py.in" conf.py @ONLY) configure_file("${CMAKE_CURRENT_SOURCE_DIR}/conf.py.in" conf.py @ONLY)
if(WITH_DOC) if(WITH_DOC)
@@ -70,6 +73,11 @@ if(SPHINX_FOUND)
-D html_theme=owncloud_com -D html_theme=owncloud_com
${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}
${SPHINX_HTML_DIR}/com ) ${SPHINX_HTML_DIR}/com )
add_custom_target( doc-man ${SPHINX_EXECUTABLE}
-q -c . -b man
-d ${SPHINX_CACHE_DIR}/man
${CMAKE_CURRENT_SOURCE_DIR}
${SPHINX_MAN_DIR} )
## Building CHM files requires HTML Help Workshop. Since it requires wine ## Building CHM files requires HTML Help Workshop. Since it requires wine
## with special dependencies, it's impossible to write a cmake check for it. ## with special dependencies, it's impossible to write a cmake check for it.
@@ -84,4 +92,4 @@ if(SPHINX_FOUND)
${SPHINX_HTMLHELP_DIR} ) ${SPHINX_HTMLHELP_DIR} )
add_custom_target( doc-chm pushd ${SPHINX_HTMLHELP_DIR}; ${MSHTML_COMPILER} *.hhp; popd add_custom_target( doc-chm pushd ${SPHINX_HTMLHELP_DIR}; ${MSHTML_COMPILER} *.hhp; popd
DEPENDS doc-chm-sphinx ) DEPENDS doc-chm-sphinx )
endif(SPHINX_FOUND) endif(SPHINX_FOUND)

View File

@@ -15,7 +15,7 @@ Configuration File
.. include:: conffile.rst .. include:: conffile.rst
Environment Variables Environment Variables
--------------------- ------------------
.. index:: env vars .. index:: env vars
.. include:: envvars.rst .. include:: envvars.rst

View File

@@ -62,4 +62,4 @@ Some interesting values that can be set on the configuration file are:
| | | ``2`` for No Proxy. | | | | ``2`` for No Proxy. |
+ + +--------------------------------------------------------------------------------------------------------+ + + +--------------------------------------------------------------------------------------------------------+
| | | ``3`` for HTTP(S) Proxy. | | | | ``3`` for HTTP(S) Proxy. |
+---------------------------------+---------------+--------------------------------------------------------------------------------------------------------+ +---------------------------------+---------------+--------------------------------------------------------------------------------------------------------+

View File

@@ -1,7 +1,7 @@
FAQ FAQ
=== ===
Some Files Are Continuously Uploaded to the Server, Even When They Are Not Modified. Some files are continuously uploaded to the server, even when they are not modified.
------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------
It is possible that another program is changing the modification date of the file. It is possible that another program is changing the modification date of the file.
@@ -11,17 +11,15 @@ continually changes all files, unless you remove
from the windows registry. from the windows registry.
See http://petersteier.wordpress.com/2011/10/22/windows-indexer-changes-modification-dates-of-eml-files/ for more information. See http://petersteier.wordpress.com/2011/10/22/windows-indexer-changes-modification-dates-of-eml-files/ for more information.
Syncing Stops When Attempting To Sync Deeper Than 100 Sub-directories. Syncing breaks when attempting to sync deeper than 50 sub-directories, but the sync client does not report an error (RC=0)
---------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------------------
The sync client has been intentionally limited to sync no deeper than 100 The sync client has been intentionally limited to sync no deeper than
sub-directories. The hard limit exists to guard against bugs with cycles fifty sub-directories, to help prevent memory problems.
like symbolic link loops. Unfortunately, it, *currently*, does not report an error when this occurs.
When a deeply nested directory is excluded from synchronization it will be However, a UI notification is planned for a future release of ownCloud.
listed with other ignored files and directories in the "Not synced" tab of
the "Activity" pane.
I Want To Move My Local Sync Folder I want to move my local sync folder
----------------------------------- -----------------------------------
The ownCloud desktop client does not provide a way to change the local sync directory. The ownCloud desktop client does not provide a way to change the local sync directory.
@@ -31,20 +29,20 @@ Specifically, you have to:
1. Remove the existing connection which syncs to the wrong directory 1. Remove the existing connection which syncs to the wrong directory
2. Add a new connection which syncs to the desired directory 2. Add a new connection which syncs to the desired directory
.. figure:: images/setup/ownCloud-remove_existing_connection.png .. image:: images/setup/ownCloud-remove_existing_connection.png
:alt: Remove an existing connection :alt: Remove an existing connection
To do so, in the client UI, which you can see above, click the "**Account**" drop-down menu and then click "Remove". To do so, in the client UI, which you can see above, click the "**Account**" drop-down menu and then click "Remove".
This will display a "**Confirm Account Removal**" dialog window. This will display a "**Confirm Account Removal**" dialog window.
.. figure:: images/setup/ownCloud-remove_existing_connection_confirmation_dialog.png .. image:: images/setup/ownCloud-remove_existing_connection_confirmation_dialog.png
:alt: Remove existing connection confirmation dialog :alt: Remove existing connection confirmation dialog
If you're sure, click "**Remove connection**". If you're sure, click "**Remove connection**".
Then, click the Account drop-down menu again, and this time click "**Add new**". Then, click the Account drop-down menu again, and this time click "**Add new**".
.. figure:: images/setup/ownCloud-replacement_connection_wizard.png .. image:: images/setup/ownCloud-replacement_connection_wizard.png
:alt: Replacement connection wizard :alt: Replacement connection wizard
This opens the ownCloud Connection Wizard, which you can see above, *but* with an extra option. This opens the ownCloud Connection Wizard, which you can see above, *but* with an extra option.

View File

@@ -3,7 +3,7 @@ Installing the Desktop Synchronization Client
============================================= =============================================
You can download the latest version of the ownCloud Desktop Synchronization You can download the latest version of the ownCloud Desktop Synchronization
Client from the `ownCloud download page`_. Client from the `ownCloud download page <https://owncloud.org/install/>`_.
There are clients for Linux, Mac OS X, and Microsoft Windows. There are clients for Linux, Mac OS X, and Microsoft Windows.
Installation on Mac OS X and Windows is the same as for any software Installation on Mac OS X and Windows is the same as for any software
@@ -58,7 +58,3 @@ synchronizing your files.
Web GUI, and one to open your local ownCloud folder Web GUI, and one to open your local ownCloud folder
Click the Finish button, and you're all done. Click the Finish button, and you're all done.
.. Links
.. _ownCloud download page: https://owncloud.com/download/#desktop-clients

View File

@@ -1,14 +0,0 @@
if(SPHINX_FOUND)
# Sphinx cache with pickled ReST documents
set(SPHINX_CACHE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_doctrees")
# HTML output directory
set(SPHINX_MAN_DIR "${CMAKE_CURRENT_BINARY_DIR}/man1")
install(DIRECTORY ${SPHINX_MAN_DIR} DESTINATION ${CMAKE_INSTALL_MANDIR} OPTIONAL)
add_custom_target( doc-man ${SPHINX_EXECUTABLE}
-c ${CMAKE_SOURCE_DIR}/doc -b man
-d ${SPHINX_CACHE_DIR}/man
${CMAKE_CURRENT_SOURCE_DIR}
${SPHINX_MAN_DIR} )
endif(SPHINX_FOUND)

View File

@@ -1 +0,0 @@

View File

@@ -1,33 +0,0 @@
:orphan:
owncloud(1)
————
SYNOPSIS
========
*owncloud* [`OPTIONS`...]
DESCRIPTION
===========
The ownCloud Client is a file synchronization desktop utility. It synchronizes files on your local computer, tablet, or handheld device with an ownCloud Server. If you make a change to the files on one device, the change is propagated to all other synchronized devices using the desktop synchronization clients.
Normally, you start the client by clicking on the desktop icon or by starting it from the client application menu. After starting, an ownCloud icon appears in the computer system tray or on your tablet or handheld device.
Options
=======
.. include:: ../doc/options.rst
Config File
===========
.. include:: ../doc/conffile.rst
BUGS
====
Please report bugs at https://github.com/owncloud/client/issues.
SEE ALSO
========
:manpage:`owncloudcmd(1)`

View File

@@ -1,97 +0,0 @@
:orphan:
owncloudcmd(1)
—————
SYNOPSIS
========
*owncloudcmd* [`OPTIONS`...] sourcedir owncloudurl
DESCRIPTION
===========
owncloudcmd is the command line tool used for the ownCloud file synchronization
desktop utility.
Contrary to the :manpage:`owncloud(1)` GUI client, `owncloudcmd` only performs
a single sync run and then exits. In so doing, `owncloudcmd` replaces the
`ocsync` binary used for the same purpose in earlier releases.
A *sync run* synchronizes a single local directory using a WebDAV share on a
remote ownCloud server.
To invoke the command line client, provide the local and the remote repository:
The first parameter is the local directory. The second parameter is
the server URL.
.. note:: Prior to the 1.6 release of owncloudcmd, the tool only accepted
``owncloud://`` or ``ownclouds://`` in place of ``http://`` and ``https://`` as
a scheme. See ``Examples`` for details.
OPTIONS
=======
``—user``, ``-u`` ``[user]``
Use ``user`` as the login name.
``—password``, ``-p`` ``[password]``
Use ``password`` as the password.
``-n``
Use ``netrc (5)`` for login.
``—non-interactive``
Do not prompt for questions.
``—silent``, ``—s``
Inhibits verbose log output.
``—trust``
Trust any SSL certificate, including invalid ones.
``—httpproxy http://[user@pass:]<server>:<port>``
Uses ``server`` as HTTP proxy.
``—nonshib``
Uses Non Shibboleth WebDAV Authentication
``—davpath [path]``
Overrides the WebDAV Path with ``path``
``—exclude [file]``
Exclude list file
``—unsyncedfolders [file]``
File containing the list of unsynced folders (selective sync)
``—max-sync-retries [n]``
Retries maximum n times (defaults to 3)
``-h``
Sync hidden files,do not ignore them
Example
=======
To synchronize the ownCloud directory ``Music`` to the local directory ``media/music``
through a proxy listening on port ``8080`` on the gateway machine ``192.168.178.1``,
the command line would be::
$ owncloudcmd —httpproxy http://192.168.178.1:8080 \
$HOME/media/music \
https://server/owncloud/remote.php/webdav/Music
``owncloudcmd`` will enquire user name and password, unless they have
been specified on the command line or ``-n`` (see `netrc(5)`) has been passed.
Using the legacy scheme, it would be::
$ owncloudcmd —httpproxy http://192.168.178.1:8080 \
$HOME/media/music \
ownclouds://server/owncloud/remote.php/webdav/Music
BUGS
====
Please report bugs at https://github.com/owncloud/client/issues.
SEE ALSO
========
:manpage:`owncloud(1)`

View File

@@ -8,6 +8,139 @@ GenericName=Folder Sync
Icon=@APPLICATION_EXECUTABLE@ Icon=@APPLICATION_EXECUTABLE@
Keywords=@APPLICATION_NAME@;syncing;file;sharing; Keywords=@APPLICATION_NAME@;syncing;file;sharing;
X-GNOME-Autostart-Delay=3 X-GNOME-Autostart-Delay=3
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations
# Translations # Translations

File diff suppressed because it is too large Load Diff

View File

@@ -115,17 +115,15 @@ extern "C" {
** a string which identifies a particular check-in of SQLite ** a string which identifies a particular check-in of SQLite
** within its configuration management system. ^The SQLITE_SOURCE_ID ** within its configuration management system. ^The SQLITE_SOURCE_ID
** string contains the date and time of the check-in (UTC) and a SHA1 ** string contains the date and time of the check-in (UTC) and a SHA1
** or SHA3-256 hash of the entire source tree. If the source code has ** or SHA3-256 hash of the entire source tree.
** been edited in any way since it was last checked in, then the last
** four hexadecimal digits of the hash may be modified.
** **
** See also: [sqlite3_libversion()], ** See also: [sqlite3_libversion()],
** [sqlite3_libversion_number()], [sqlite3_sourceid()], ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
** [sqlite_version()] and [sqlite_source_id()]. ** [sqlite_version()] and [sqlite_source_id()].
*/ */
#define SQLITE_VERSION "3.21.0" #define SQLITE_VERSION "3.20.1"
#define SQLITE_VERSION_NUMBER 3021000 #define SQLITE_VERSION_NUMBER 3020001
#define SQLITE_SOURCE_ID "2017-10-24 18:55:49 1a584e499906b5c87ec7d43d4abce641fdf017c42125b083109bc77c4de48827" #define SQLITE_SOURCE_ID "2017-08-24 16:21:36 8d3a7ea6c5690d6b7c3767558f4f01b511c55463e3f9e64506801fe9b74dce34"
/* /*
** CAPI3REF: Run-Time Library Version Numbers ** CAPI3REF: Run-Time Library Version Numbers
@@ -141,7 +139,7 @@ extern "C" {
** **
** <blockquote><pre> ** <blockquote><pre>
** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER ); ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
** assert( strncmp(sqlite3_sourceid(),SQLITE_SOURCE_ID,80)==0 ); ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 ); ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
** </pre></blockquote>)^ ** </pre></blockquote>)^
** **
@@ -151,11 +149,9 @@ extern "C" {
** function is provided for use in DLLs since DLL users usually do not have ** function is provided for use in DLLs since DLL users usually do not have
** direct access to string constants within the DLL. ^The ** direct access to string constants within the DLL. ^The
** sqlite3_libversion_number() function returns an integer equal to ** sqlite3_libversion_number() function returns an integer equal to
** [SQLITE_VERSION_NUMBER]. ^(The sqlite3_sourceid() function returns ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
** a pointer to a string constant whose value is the same as the ** a pointer to a string constant whose value is the same as the
** [SQLITE_SOURCE_ID] C preprocessor macro. Except if SQLite is built ** [SQLITE_SOURCE_ID] C preprocessor macro.
** using an edited copy of [the amalgamation], then the last four characters
** of the hash might be different from [SQLITE_SOURCE_ID].)^
** **
** See also: [sqlite_version()] and [sqlite_source_id()]. ** See also: [sqlite_version()] and [sqlite_source_id()].
*/ */
@@ -436,7 +432,7 @@ SQLITE_API int sqlite3_exec(
#define SQLITE_FULL 13 /* Insertion failed because database is full */ #define SQLITE_FULL 13 /* Insertion failed because database is full */
#define SQLITE_CANTOPEN 14 /* Unable to open the database file */ #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
#define SQLITE_PROTOCOL 15 /* Database lock protocol error */ #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
#define SQLITE_EMPTY 16 /* Internal use only */ #define SQLITE_EMPTY 16 /* Not used */
#define SQLITE_SCHEMA 17 /* The database schema changed */ #define SQLITE_SCHEMA 17 /* The database schema changed */
#define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */ #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
#define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */ #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
@@ -498,9 +494,6 @@ SQLITE_API int sqlite3_exec(
#define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8)) #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
#define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8)) #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
#define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8)) #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
#define SQLITE_IOERR_BEGIN_ATOMIC (SQLITE_IOERR | (29<<8))
#define SQLITE_IOERR_COMMIT_ATOMIC (SQLITE_IOERR | (30<<8))
#define SQLITE_IOERR_ROLLBACK_ATOMIC (SQLITE_IOERR | (31<<8))
#define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8)) #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
#define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8)) #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
#define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8)) #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
@@ -587,11 +580,6 @@ SQLITE_API int sqlite3_exec(
** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
** read-only media and cannot be changed even by processes with ** read-only media and cannot be changed even by processes with
** elevated privileges. ** elevated privileges.
**
** The SQLITE_IOCAP_BATCH_ATOMIC property means that the underlying
** filesystem supports doing multiple write operations atomically when those
** write operations are bracketed by [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] and
** [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE].
*/ */
#define SQLITE_IOCAP_ATOMIC 0x00000001 #define SQLITE_IOCAP_ATOMIC 0x00000001
#define SQLITE_IOCAP_ATOMIC512 0x00000002 #define SQLITE_IOCAP_ATOMIC512 0x00000002
@@ -607,7 +595,6 @@ SQLITE_API int sqlite3_exec(
#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
#define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
#define SQLITE_IOCAP_IMMUTABLE 0x00002000 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
#define SQLITE_IOCAP_BATCH_ATOMIC 0x00004000
/* /*
** CAPI3REF: File Locking Levels ** CAPI3REF: File Locking Levels
@@ -742,7 +729,6 @@ struct sqlite3_file {
** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN] ** <li> [SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN]
** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE] ** <li> [SQLITE_IOCAP_POWERSAFE_OVERWRITE]
** <li> [SQLITE_IOCAP_IMMUTABLE] ** <li> [SQLITE_IOCAP_IMMUTABLE]
** <li> [SQLITE_IOCAP_BATCH_ATOMIC]
** </ul> ** </ul>
** **
** The SQLITE_IOCAP_ATOMIC property means that all writes of ** The SQLITE_IOCAP_ATOMIC property means that all writes of
@@ -1026,40 +1012,6 @@ struct sqlite3_io_methods {
** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
** this opcode. ** this opcode.
**
** <li>[[SQLITE_FCNTL_BEGIN_ATOMIC_WRITE]]
** If the [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] opcode returns SQLITE_OK, then
** the file descriptor is placed in "batch write mode", which
** means all subsequent write operations will be deferred and done
** atomically at the next [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]. Systems
** that do not support batch atomic writes will return SQLITE_NOTFOUND.
** ^Following a successful SQLITE_FCNTL_BEGIN_ATOMIC_WRITE and prior to
** the closing [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] or
** [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE], SQLite will make
** no VFS interface calls on the same [sqlite3_file] file descriptor
** except for calls to the xWrite method and the xFileControl method
** with [SQLITE_FCNTL_SIZE_HINT].
**
** <li>[[SQLITE_FCNTL_COMMIT_ATOMIC_WRITE]]
** The [SQLITE_FCNTL_COMMIT_ATOMIC_WRITE] opcode causes all write
** operations since the previous successful call to
** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be performed atomically.
** This file control returns [SQLITE_OK] if and only if the writes were
** all performed successfully and have been committed to persistent storage.
** ^Regardless of whether or not it is successful, this file control takes
** the file descriptor out of batch write mode so that all subsequent
** write operations are independent.
** ^SQLite will never invoke SQLITE_FCNTL_COMMIT_ATOMIC_WRITE without
** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
**
** <li>[[SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE]]
** The [SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE] opcode causes all write
** operations since the previous successful call to
** [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE] to be rolled back.
** ^This file control takes the file descriptor out of batch write mode
** so that all subsequent write operations are independent.
** ^SQLite will never invoke SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE without
** a prior successful call to [SQLITE_FCNTL_BEGIN_ATOMIC_WRITE].
** </ul> ** </ul>
*/ */
#define SQLITE_FCNTL_LOCKSTATE 1 #define SQLITE_FCNTL_LOCKSTATE 1
@@ -1091,9 +1043,6 @@ struct sqlite3_io_methods {
#define SQLITE_FCNTL_JOURNAL_POINTER 28 #define SQLITE_FCNTL_JOURNAL_POINTER 28
#define SQLITE_FCNTL_WIN32_GET_HANDLE 29 #define SQLITE_FCNTL_WIN32_GET_HANDLE 29
#define SQLITE_FCNTL_PDB 30 #define SQLITE_FCNTL_PDB 30
#define SQLITE_FCNTL_BEGIN_ATOMIC_WRITE 31
#define SQLITE_FCNTL_COMMIT_ATOMIC_WRITE 32
#define SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE 33
/* deprecated names */ /* deprecated names */
#define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
@@ -1664,16 +1613,6 @@ struct sqlite3_mem_methods {
** routines with a wrapper that simulations memory allocation failure or ** routines with a wrapper that simulations memory allocation failure or
** tracks memory usage, for example. </dd> ** tracks memory usage, for example. </dd>
** **
** [[SQLITE_CONFIG_SMALL_MALLOC]] <dt>SQLITE_CONFIG_SMALL_MALLOC</dt>
** <dd> ^The SQLITE_CONFIG_SMALL_MALLOC option takes single argument of
** type int, interpreted as a boolean, which if true provides a hint to
** SQLite that it should avoid large memory allocations if possible.
** SQLite will run faster if it is free to make large memory allocations,
** but some application might prefer to run slower in exchange for
** guarantees about memory fragmentation that are possible if large
** allocations are avoided. This hint is normally off.
** </dd>
**
** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt> ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int, ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
** interpreted as a boolean, which enables or disables the collection of ** interpreted as a boolean, which enables or disables the collection of
@@ -1691,7 +1630,25 @@ struct sqlite3_mem_methods {
** </dd> ** </dd>
** **
** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt> ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
** <dd> The SQLITE_CONFIG_SCRATCH option is no longer used. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
** that SQLite can use for scratch memory. ^(There are three arguments
** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
** aligned memory buffer from which the scratch allocations will be
** drawn, the size of each scratch allocation (sz),
** and the maximum number of scratch allocations (N).)^
** The first argument must be a pointer to an 8-byte aligned buffer
** of at least sz*N bytes of memory.
** ^SQLite will not use more than one scratch buffers per thread.
** ^SQLite will never request a scratch buffer that is more than 6
** times the database page size.
** ^If SQLite needs needs additional
** scratch memory beyond what is provided by this configuration option, then
** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
** ^When the application provides any amount of scratch memory using
** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
** [sqlite3_malloc|heap allocations].
** This can help [Robson proof|prevent memory allocation failures] due to heap
** fragmentation in low-memory embedded systems.
** </dd> ** </dd>
** **
** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt> ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
@@ -1727,7 +1684,8 @@ struct sqlite3_mem_methods {
** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt> ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
** that SQLite will use for all of its dynamic memory allocation needs ** that SQLite will use for all of its dynamic memory allocation needs
** beyond those provided for by [SQLITE_CONFIG_PAGECACHE]. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
** [SQLITE_CONFIG_PAGECACHE].
** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
** [SQLITE_ERROR] if invoked otherwise. ** [SQLITE_ERROR] if invoked otherwise.
@@ -1920,7 +1878,7 @@ struct sqlite3_mem_methods {
#define SQLITE_CONFIG_SERIALIZED 3 /* nil */ #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
#define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */ #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
#define SQLITE_CONFIG_SCRATCH 6 /* No longer used */ #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
#define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */ #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
#define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */ #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
#define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */ #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
@@ -1941,7 +1899,6 @@ struct sqlite3_mem_methods {
#define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */ #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
#define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */ #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
#define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */ #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
#define SQLITE_CONFIG_SMALL_MALLOC 27 /* boolean */
/* /*
** CAPI3REF: Database Connection Configuration Options ** CAPI3REF: Database Connection Configuration Options
@@ -3142,10 +3099,10 @@ SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
** ^If [URI filename] interpretation is enabled, and the filename argument ** ^If [URI filename] interpretation is enabled, and the filename argument
** begins with "file:", then the filename is interpreted as a URI. ^URI ** begins with "file:", then the filename is interpreted as a URI. ^URI
** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
** set in the third argument to sqlite3_open_v2(), or if it has ** set in the fourth argument to sqlite3_open_v2(), or if it has
** been enabled globally using the [SQLITE_CONFIG_URI] option with the ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
** URI filename interpretation is turned off ** As of SQLite version 3.7.7, URI filename interpretation is turned off
** by default, but future releases of SQLite might enable URI filename ** by default, but future releases of SQLite might enable URI filename
** interpretation by default. See "[URI filenames]" for additional ** interpretation by default. See "[URI filenames]" for additional
** information. ** information.
@@ -3819,9 +3776,8 @@ SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
** implementation of [application-defined SQL functions] are protected. ** implementation of [application-defined SQL functions] are protected.
** ^The sqlite3_value object returned by ** ^The sqlite3_value object returned by
** [sqlite3_column_value()] is unprotected. ** [sqlite3_column_value()] is unprotected.
** Unprotected sqlite3_value objects may only be used as arguments ** Unprotected sqlite3_value objects may only be used with
** to [sqlite3_result_value()], [sqlite3_bind_value()], and ** [sqlite3_result_value()] and [sqlite3_bind_value()].
** [sqlite3_value_dup()].
** The [sqlite3_value_blob | sqlite3_value_type()] family of ** The [sqlite3_value_blob | sqlite3_value_type()] family of
** interfaces require protected sqlite3_value objects. ** interfaces require protected sqlite3_value objects.
*/ */
@@ -4243,7 +4199,7 @@ SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
** other than [SQLITE_ROW] before any subsequent invocation of ** other than [SQLITE_ROW] before any subsequent invocation of
** sqlite3_step(). Failure to reset the prepared statement using ** sqlite3_step(). Failure to reset the prepared statement using
** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1], ** sqlite3_step(). But after [version 3.6.23.1] ([dateof:3.6.23.1]),
** sqlite3_step() began ** sqlite3_step() began
** calling [sqlite3_reset()] automatically in this circumstance rather ** calling [sqlite3_reset()] automatically in this circumstance rather
** than returning [SQLITE_MISUSE]. This is not considered a compatibility ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
@@ -6247,20 +6203,15 @@ struct sqlite3_index_info {
** an operator that is part of a constraint term in the wHERE clause of ** an operator that is part of a constraint term in the wHERE clause of
** a query that uses a [virtual table]. ** a query that uses a [virtual table].
*/ */
#define SQLITE_INDEX_CONSTRAINT_EQ 2 #define SQLITE_INDEX_CONSTRAINT_EQ 2
#define SQLITE_INDEX_CONSTRAINT_GT 4 #define SQLITE_INDEX_CONSTRAINT_GT 4
#define SQLITE_INDEX_CONSTRAINT_LE 8 #define SQLITE_INDEX_CONSTRAINT_LE 8
#define SQLITE_INDEX_CONSTRAINT_LT 16 #define SQLITE_INDEX_CONSTRAINT_LT 16
#define SQLITE_INDEX_CONSTRAINT_GE 32 #define SQLITE_INDEX_CONSTRAINT_GE 32
#define SQLITE_INDEX_CONSTRAINT_MATCH 64 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
#define SQLITE_INDEX_CONSTRAINT_LIKE 65 #define SQLITE_INDEX_CONSTRAINT_LIKE 65
#define SQLITE_INDEX_CONSTRAINT_GLOB 66 #define SQLITE_INDEX_CONSTRAINT_GLOB 66
#define SQLITE_INDEX_CONSTRAINT_REGEXP 67 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
#define SQLITE_INDEX_CONSTRAINT_NE 68
#define SQLITE_INDEX_CONSTRAINT_ISNOT 69
#define SQLITE_INDEX_CONSTRAINT_ISNOTNULL 70
#define SQLITE_INDEX_CONSTRAINT_ISNULL 71
#define SQLITE_INDEX_CONSTRAINT_IS 72
/* /*
** CAPI3REF: Register A Virtual Table Implementation ** CAPI3REF: Register A Virtual Table Implementation
@@ -7012,7 +6963,7 @@ SQLITE_API int sqlite3_test_control(int op, ...);
#define SQLITE_TESTCTRL_RESERVE 14 #define SQLITE_TESTCTRL_RESERVE 14
#define SQLITE_TESTCTRL_OPTIMIZATIONS 15 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
#define SQLITE_TESTCTRL_ISKEYWORD 16 #define SQLITE_TESTCTRL_ISKEYWORD 16
#define SQLITE_TESTCTRL_SCRATCHMALLOC 17 /* NOT USED */ #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
#define SQLITE_TESTCTRL_LOCALTIME_FAULT 18 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
#define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */ #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
#define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19 #define SQLITE_TESTCTRL_ONCE_RESET_THRESHOLD 19
@@ -7071,7 +7022,8 @@ SQLITE_API int sqlite3_status64(
** <dd>This parameter is the current amount of memory checked out ** <dd>This parameter is the current amount of memory checked out
** using [sqlite3_malloc()], either directly or indirectly. The ** using [sqlite3_malloc()], either directly or indirectly. The
** figure includes calls made to [sqlite3_malloc()] by the application ** figure includes calls made to [sqlite3_malloc()] by the application
** and internal memory usage by the SQLite library. Auxiliary page-cache ** and internal memory usage by the SQLite library. Scratch memory
** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
** this parameter. The amount returned is the sum of the allocation ** this parameter. The amount returned is the sum of the allocation
** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^ ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
@@ -7109,14 +7061,29 @@ SQLITE_API int sqlite3_status64(
** *pHighwater parameter to [sqlite3_status()] is of interest. ** *pHighwater parameter to [sqlite3_status()] is of interest.
** The value written into the *pCurrent parameter is undefined.</dd>)^ ** The value written into the *pCurrent parameter is undefined.</dd>)^
** **
** [[SQLITE_STATUS_SCRATCH_USED]] <dt>SQLITE_STATUS_SCRATCH_USED</dt> ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
** <dd>No longer used.</dd> ** <dd>This parameter returns the number of allocations used out of the
** [scratch memory allocator] configured using
** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
** in bytes. Since a single thread may only have one scratch allocation
** outstanding at time, this parameter also reports the number of threads
** using scratch memory at the same time.</dd>)^
** **
** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt> ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
** <dd>No longer used.</dd> ** <dd>This parameter returns the number of bytes of scratch memory
** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
** buffer and where forced to overflow to [sqlite3_malloc()]. The values
** returned include overflows because the requested allocation was too
** larger (that is, because the requested allocation was larger than the
** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
** slots were available.
** </dd>)^
** **
** [[SQLITE_STATUS_SCRATCH_SIZE]] <dt>SQLITE_STATUS_SCRATCH_SIZE</dt> ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
** <dd>No longer used.</dd> ** <dd>This parameter records the largest memory allocation request
** handed to [scratch memory allocator]. Only the value returned in the
** *pHighwater parameter to [sqlite3_status()] is of interest.
** The value written into the *pCurrent parameter is undefined.</dd>)^
** **
** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt> ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
** <dd>The *pHighwater parameter records the deepest parser stack. ** <dd>The *pHighwater parameter records the deepest parser stack.
@@ -7129,12 +7096,12 @@ SQLITE_API int sqlite3_status64(
#define SQLITE_STATUS_MEMORY_USED 0 #define SQLITE_STATUS_MEMORY_USED 0
#define SQLITE_STATUS_PAGECACHE_USED 1 #define SQLITE_STATUS_PAGECACHE_USED 1
#define SQLITE_STATUS_PAGECACHE_OVERFLOW 2 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
#define SQLITE_STATUS_SCRATCH_USED 3 /* NOT USED */ #define SQLITE_STATUS_SCRATCH_USED 3
#define SQLITE_STATUS_SCRATCH_OVERFLOW 4 /* NOT USED */ #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
#define SQLITE_STATUS_MALLOC_SIZE 5 #define SQLITE_STATUS_MALLOC_SIZE 5
#define SQLITE_STATUS_PARSER_STACK 6 #define SQLITE_STATUS_PARSER_STACK 6
#define SQLITE_STATUS_PAGECACHE_SIZE 7 #define SQLITE_STATUS_PAGECACHE_SIZE 7
#define SQLITE_STATUS_SCRATCH_SIZE 8 /* NOT USED */ #define SQLITE_STATUS_SCRATCH_SIZE 8
#define SQLITE_STATUS_MALLOC_COUNT 9 #define SQLITE_STATUS_MALLOC_COUNT 9
/* /*
@@ -9231,8 +9198,8 @@ SQLITE_API int sqlite3session_diff(
*/ */
SQLITE_API int sqlite3session_patchset( SQLITE_API int sqlite3session_patchset(
sqlite3_session *pSession, /* Session object */ sqlite3_session *pSession, /* Session object */
int *pnPatchset, /* OUT: Size of buffer at *ppPatchset */ int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
void **ppPatchset /* OUT: Buffer containing patchset */ void **ppPatchset /* OUT: Buffer containing changeset */
); );
/* /*
@@ -9999,12 +9966,12 @@ SQLITE_API int sqlite3changeset_apply(
** **
** <table border=1 style="margin-left:8ex;margin-right:8ex"> ** <table border=1 style="margin-left:8ex;margin-right:8ex">
** <tr><th>Streaming function<th>Non-streaming equivalent</th> ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
** <tr><td>sqlite3changeset_apply_strm<td>[sqlite3changeset_apply] ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
** <tr><td>sqlite3changeset_concat_strm<td>[sqlite3changeset_concat] ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
** <tr><td>sqlite3changeset_invert_strm<td>[sqlite3changeset_invert] ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
** <tr><td>sqlite3changeset_start_strm<td>[sqlite3changeset_start] ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
** <tr><td>sqlite3session_changeset_strm<td>[sqlite3session_changeset] ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
** <tr><td>sqlite3session_patchset_strm<td>[sqlite3session_patchset] ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
** </table> ** </table>
** **
** Non-streaming functions that accept changesets (or patchsets) as input ** Non-streaming functions that accept changesets (or patchsets) as input

View File

@@ -13,18 +13,8 @@ if(WIN32)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--nxcompat -Wl,--dynamicbase") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--nxcompat -Wl,--dynamicbase")
set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--nxcompat -Wl,--dynamicbase") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--nxcompat -Wl,--dynamicbase")
elseif(UNIX AND NOT APPLE) elseif(UNIX AND NOT APPLE)
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector-strong")
if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.9) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector-strong")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector-strong")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector-strong")
else()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector --param=ssp-buffer-size=4")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector --param=ssp-buffer-size=4")
endif()
else()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fstack-protector-strong")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fstack-protector-strong")
endif()
string(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE_LOWER) string(TOLOWER "${CMAKE_BUILD_TYPE}" CMAKE_BUILD_TYPE_LOWER)
if(CMAKE_BUILD_TYPE_LOWER MATCHES "(release|relwithdebinfo|minsizerel)") if(CMAKE_BUILD_TYPE_LOWER MATCHES "(release|relwithdebinfo|minsizerel)")

View File

@@ -20,14 +20,13 @@ include_directories(${CMAKE_SOURCE_DIR}/src/csync
include_directories(${CMAKE_SOURCE_DIR}/src/3rdparty/qtokenizer) include_directories(${CMAKE_SOURCE_DIR}/src/3rdparty/qtokenizer)
if(UNIX AND NOT APPLE) if(UNIX AND NOT APPLE)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIE") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pie -fPIE")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIE") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pie -fPIE")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pie")
endif() endif()
if(NOT BUILD_LIBRARIES_ONLY) if(NOT BUILD_LIBRARIES_ONLY)
add_executable(${cmd_NAME} ${cmd_SRC}) add_executable(${cmd_NAME} ${cmd_SRC})
qt5_use_modules(${cmd_NAME} Network ) qt5_use_modules(${cmd_NAME} Network Sql)
set_target_properties(${cmd_NAME} PROPERTIES set_target_properties(${cmd_NAME} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY ${BIN_OUTPUT_DIRECTORY} ) RUNTIME_OUTPUT_DIRECTORY ${BIN_OUTPUT_DIRECTORY} )
set_target_properties(${cmd_NAME} PROPERTIES set_target_properties(${cmd_NAME} PROPERTIES

View File

@@ -39,7 +39,6 @@
#include "theme.h" #include "theme.h"
#include "netrcparser.h" #include "netrcparser.h"
#include "libsync/logger.h"
#include "config.h" #include "config.h"
@@ -190,7 +189,7 @@ void help()
std::cout << " --downlimit [n] Limit the download speed of files to n KB/s" << std::endl; std::cout << " --downlimit [n] Limit the download speed of files to n KB/s" << std::endl;
std::cout << " -h Sync hidden files,do not ignore them" << std::endl; std::cout << " -h Sync hidden files,do not ignore them" << std::endl;
std::cout << " --version, -v Display version and exit" << std::endl; std::cout << " --version, -v Display version and exit" << std::endl;
std::cout << " --logdebug More verbose logging" << std::endl; std::cout << " --debug More verbose logging" << std::endl;
std::cout << "" << std::endl; std::cout << "" << std::endl;
exit(0); exit(0);
} }
@@ -268,9 +267,6 @@ void parseOptions(const QStringList &app_args, CmdOptions *options)
options->uplimit = it.next().toInt() * 1000; options->uplimit = it.next().toInt() * 1000;
} else if (option == "--downlimit" && !it.peekNext().startsWith("-")) { } else if (option == "--downlimit" && !it.peekNext().startsWith("-")) {
options->downlimit = it.next().toInt() * 1000; options->downlimit = it.next().toInt() * 1000;
} else if (option == "--logdebug") {
Logger::instance()->setLogFile("-");
Logger::instance()->setLogDebug(true);
} else { } else {
help(); help();
} }
@@ -334,8 +330,6 @@ int main(int argc, char **argv)
csync_set_log_level(options.silent ? 1 : 11); csync_set_log_level(options.silent ? 1 : 11);
if (options.silent) { if (options.silent) {
qInstallMsgHandler(nullMessageHandler); qInstallMsgHandler(nullMessageHandler);
} else {
qSetMessagePattern("%{time MM-dd hh:mm:ss:zzz} [ %{type} %{category} ]%{if-debug}\t[ %{function} ]%{endif}:\t%{message}");
} }
AccountPtr account = Account::create(); AccountPtr account = Account::create();

View File

@@ -90,21 +90,6 @@ QByteArray makeChecksumHeader(const QByteArray &checksumType, const QByteArray &
return header; return header;
} }
QByteArray findBestChecksum(const QByteArray &checksums)
{
int i = 0;
// The order of the searches here defines the preference ordering.
if (-1 != (i = checksums.indexOf("SHA1:"))
|| -1 != (i = checksums.indexOf("MD5:"))
|| -1 != (i = checksums.indexOf("Adler32:"))) {
// Now i is the start of the best checksum
// Grab it until the next space or end of string.
auto checksum = checksums.mid(i);
return checksum.mid(0, checksum.indexOf(" "));
}
return QByteArray();
}
bool parseChecksumHeader(const QByteArray &header, QByteArray *type, QByteArray *checksum) bool parseChecksumHeader(const QByteArray &header, QByteArray *type, QByteArray *checksum)
{ {
if (header.isEmpty()) { if (header.isEmpty()) {
@@ -135,7 +120,7 @@ QByteArray parseChecksumHeaderType(const QByteArray &header)
bool uploadChecksumEnabled() bool uploadChecksumEnabled()
{ {
static bool enabled = qEnvironmentVariableIsEmpty("OWNCLOUD_DISABLE_CHECKSUM_UPLOAD"); static bool enabled = qgetenv("OWNCLOUD_DISABLE_CHECKSUM_UPLOAD").isEmpty();
return enabled; return enabled;
} }
@@ -148,12 +133,6 @@ QByteArray contentChecksumType()
return type; return type;
} }
static bool checksumComputationEnabled()
{
static bool enabled = qgetenv("OWNCLOUD_DISABLE_CHECKSUM_COMPUTATIONS").isEmpty();
return enabled;
}
ComputeChecksum::ComputeChecksum(QObject *parent) ComputeChecksum::ComputeChecksum(QObject *parent)
: QObject(parent) : QObject(parent)
{ {
@@ -171,8 +150,6 @@ QByteArray ComputeChecksum::checksumType() const
void ComputeChecksum::start(const QString &filePath) void ComputeChecksum::start(const QString &filePath)
{ {
qCInfo(lcChecksums) << "Computing" << checksumType() << "checksum of" << filePath << "in a thread";
// Calculate the checksum in a different thread first. // Calculate the checksum in a different thread first.
connect(&_watcher, &QFutureWatcherBase::finished, connect(&_watcher, &QFutureWatcherBase::finished,
this, &ComputeChecksum::slotCalculationDone, this, &ComputeChecksum::slotCalculationDone,
@@ -182,11 +159,6 @@ void ComputeChecksum::start(const QString &filePath)
QByteArray ComputeChecksum::computeNow(const QString &filePath, const QByteArray &checksumType) QByteArray ComputeChecksum::computeNow(const QString &filePath, const QByteArray &checksumType)
{ {
if (!checksumComputationEnabled()) {
qCWarning(lcChecksums) << "Checksum computation disabled by environment variable";
return QByteArray();
}
if (checksumType == checkSumMD5C) { if (checksumType == checkSumMD5C) {
return FileSystem::calcMd5(filePath); return FileSystem::calcMd5(filePath);
} else if (checksumType == checkSumSHA1C) { } else if (checksumType == checkSumSHA1C) {
@@ -265,7 +237,6 @@ QByteArray CSyncChecksumHook::hook(const QByteArray &path, const QByteArray &oth
if (type.isEmpty()) if (type.isEmpty())
return NULL; return NULL;
qCInfo(lcChecksums) << "Computing" << type << "checksum of" << path << "in the csync hook";
QByteArray checksum = ComputeChecksum::computeNow(QString::fromUtf8(path), type); QByteArray checksum = ComputeChecksum::computeNow(QString::fromUtf8(path), type);
if (checksum.isNull()) { if (checksum.isNull()) {
qCWarning(lcChecksums) << "Failed to compute checksum" << type << "for" << path; qCWarning(lcChecksums) << "Failed to compute checksum" << type << "for" << path;

View File

@@ -36,16 +36,6 @@ static const char checkSumAdlerC[] = "Adler32";
class SyncJournalDb; class SyncJournalDb;
/**
* Returns the highest-quality checksum in a 'checksums'
* property retrieved from the server.
*
* Example: "ADLER32:1231 SHA1:ab124124 MD5:2131affa21"
* -> "SHA1:ab124124"
*/
OCSYNC_EXPORT QByteArray findBestChecksum(const QByteArray &checksums);
/// Creates a checksum header from type and value. /// Creates a checksum header from type and value.
OCSYNC_EXPORT QByteArray makeChecksumHeader(const QByteArray &checksumType, const QByteArray &checksum); OCSYNC_EXPORT QByteArray makeChecksumHeader(const QByteArray &checksumType, const QByteArray &checksum);

View File

@@ -358,19 +358,26 @@ QString FileSystem::fileSystemForPath(const QString &path)
#define BUFSIZE qint64(500 * 1024) // 500 KiB #define BUFSIZE qint64(500 * 1024) // 500 KiB
static QByteArray readToCrypto( const QString& filename, QCryptographicHash::Algorithm algo ) static QByteArray readToCrypto(const QString &filename, QCryptographicHash::Algorithm algo)
{ {
QFile file(filename); QFile file(filename);
QByteArray arr; const qint64 bufSize = qMin(BUFSIZE, file.size() + 1);
QCryptographicHash crypto( algo ); QByteArray buf(bufSize, Qt::Uninitialized);
QByteArray arr;
QCryptographicHash crypto(algo);
if (file.open(QIODevice::ReadOnly)) { if (file.open(QIODevice::ReadOnly)) {
if (crypto.addData(&file)) { qint64 size;
arr = crypto.result().toHex(); while (!file.atEnd()) {
} size = file.read(buf.data(), bufSize);
} if (size > 0) {
return arr; crypto.addData(buf.data(), size);
} }
}
arr = crypto.result().toHex();
}
return arr;
}
QByteArray FileSystem::calcMd5(const QString &filename) QByteArray FileSystem::calcMd5(const QString &filename)
{ {

View File

@@ -85,32 +85,24 @@ bool SqlDatabase::openHelper(const QString &filename, int sqliteFlags)
return true; return true;
} }
SqlDatabase::CheckDbResult SqlDatabase::checkDb() bool SqlDatabase::checkDb()
{ {
// quick_check can fail with a disk IO error when diskspace is low // quick_check can fail with a disk IO error when diskspace is low
SqlQuery quick_check(*this); SqlQuery quick_check(*this);
quick_check.prepare("PRAGMA quick_check;", /*allow_failure=*/true);
if (quick_check.prepare("PRAGMA quick_check;", /*allow_failure=*/true) != SQLITE_OK) {
qCWarning(lcSql) << "Error preparing quick_check on database";
_errId = quick_check.errorId();
_error = quick_check.error();
return CheckDbResult::CantPrepare;
}
if (!quick_check.exec()) { if (!quick_check.exec()) {
qCWarning(lcSql) << "Error running quick_check on database"; qCWarning(lcSql) << "Error running quick_check on database";
_errId = quick_check.errorId(); return false;
_error = quick_check.error();
return CheckDbResult::CantExec;
} }
quick_check.next(); quick_check.next();
QString result = quick_check.stringValue(0); QString result = quick_check.stringValue(0);
if (result != "ok") { if (result != "ok") {
qCWarning(lcSql) << "quick_check returned failure:" << result; qCWarning(lcSql) << "quick_check returned failure:" << result;
return CheckDbResult::NotOk; return false;
} }
return CheckDbResult::Ok; return true;
} }
bool SqlDatabase::openOrCreateReadWrite(const QString &filename) bool SqlDatabase::openOrCreateReadWrite(const QString &filename)
@@ -123,25 +115,13 @@ bool SqlDatabase::openOrCreateReadWrite(const QString &filename)
return false; return false;
} }
auto checkResult = checkDb(); if (!checkDb()) {
if (checkResult != CheckDbResult::Ok) { // When disk space is low, checking the db may fail even though it's fine.
if (checkResult == CheckDbResult::CantPrepare) { qint64 freeSpace = Utility::freeDiskSpace(QFileInfo(filename).dir().absolutePath());
// When disk space is low, preparing may fail even though the db is fine. if (freeSpace != -1 && freeSpace < 1000000) {
// Typically CANTOPEN or IOERR. qCWarning(lcSql) << "Consistency check failed, disk space is low, aborting" << freeSpace;
qint64 freeSpace = Utility::freeDiskSpace(QFileInfo(filename).dir().absolutePath()); close();
if (freeSpace != -1 && freeSpace < 1000000) { return false;
qCWarning(lcSql) << "Can't prepare consistency check and disk space is low:" << freeSpace;
close();
return false;
}
// Even when there's enough disk space, it might very well be that the
// file is on a read-only filesystem and can't be opened because of that.
if (_errId == SQLITE_CANTOPEN) {
qCWarning(lcSql) << "Can't open db to prepare consistency check, aborting";
close();
return false;
}
} }
qCCritical(lcSql) << "Consistency check failed, removing broken db" << filename; qCCritical(lcSql) << "Consistency check failed, removing broken db" << filename;
@@ -164,7 +144,7 @@ bool SqlDatabase::openReadOnly(const QString &filename)
return false; return false;
} }
if (checkDb() != CheckDbResult::Ok) { if (!checkDb()) {
qCWarning(lcSql) << "Consistency check failed in readonly mode, giving up" << filename; qCWarning(lcSql) << "Consistency check failed in readonly mode, giving up" << filename;
close(); close();
return false; return false;
@@ -184,8 +164,8 @@ void SqlDatabase::close()
{ {
if (_db) { if (_db) {
SQLITE_DO(sqlite3_close(_db)); SQLITE_DO(sqlite3_close(_db));
if (_errId != SQLITE_OK) // Fatal because reopening an unclosed db might be problematic.
qCWarning(lcSql) << "Closing database failed" << _error; ENFORCE(_errId == SQLITE_OK, "Error when closing DB");
_db = 0; _db = 0;
} }
} }

View File

@@ -48,15 +48,8 @@ public:
sqlite3 *sqliteDb(); sqlite3 *sqliteDb();
private: private:
enum class CheckDbResult {
Ok,
CantPrepare,
CantExec,
NotOk,
};
bool openHelper(const QString &filename, int sqliteFlags); bool openHelper(const QString &filename, int sqliteFlags);
CheckDbResult checkDb(); bool checkDb();
sqlite3 *_db; sqlite3 *_db;
QString _error; // last error string QString _error; // last error string

View File

@@ -1094,10 +1094,15 @@ bool SyncJournalDb::getFileRecordByInode(quint64 inode, SyncJournalFileRecord *r
return true; return true;
} }
bool SyncJournalDb::getFileRecordsByFileId(const QByteArray &fileId, const std::function<void(const SyncJournalFileRecord &)> &rowCallback) bool SyncJournalDb::getFileRecordByFileId(const QByteArray &fileId, SyncJournalFileRecord *rec)
{ {
QMutexLocker locker(&_mutex); QMutexLocker locker(&_mutex);
// Reset the output var in case the caller is reusing it.
Q_ASSERT(rec);
rec->_path.clear();
Q_ASSERT(!rec->isValid());
if (fileId.isEmpty() || _metadataTableIsEmpty) if (fileId.isEmpty() || _metadataTableIsEmpty)
return true; // no error, yet nothing found (rec->isValid() == false) return true; // no error, yet nothing found (rec->isValid() == false)
@@ -1111,10 +1116,8 @@ bool SyncJournalDb::getFileRecordsByFileId(const QByteArray &fileId, const std::
return false; return false;
} }
while (_getFileRecordQueryByFileId->next()) { if (_getFileRecordQueryByFileId->next()) {
SyncJournalFileRecord rec; fillFileRecordFromGetQuery(*rec, *_getFileRecordQueryByFileId);
fillFileRecordFromGetQuery(rec, *_getFileRecordQueryByFileId);
rowCallback(rec);
} }
return true; return true;

View File

@@ -58,7 +58,7 @@ public:
bool getFileRecord(const QString &filename, SyncJournalFileRecord *rec) { return getFileRecord(filename.toUtf8(), rec); } bool getFileRecord(const QString &filename, SyncJournalFileRecord *rec) { return getFileRecord(filename.toUtf8(), rec); }
bool getFileRecord(const QByteArray &filename, SyncJournalFileRecord *rec); bool getFileRecord(const QByteArray &filename, SyncJournalFileRecord *rec);
bool getFileRecordByInode(quint64 inode, SyncJournalFileRecord *rec); bool getFileRecordByInode(quint64 inode, SyncJournalFileRecord *rec);
bool getFileRecordsByFileId(const QByteArray &fileId, const std::function<void(const SyncJournalFileRecord &)> &rowCallback); bool getFileRecordByFileId(const QByteArray &fileId, SyncJournalFileRecord *rec);
bool getFilesBelowPath(const QByteArray &path, const std::function<void(const SyncJournalFileRecord&)> &rowCallback); bool getFilesBelowPath(const QByteArray &path, const std::function<void(const SyncJournalFileRecord&)> &rowCallback);
bool setFileRecord(const SyncJournalFileRecord &record); bool setFileRecord(const SyncJournalFileRecord &record);

View File

@@ -579,7 +579,7 @@ bool Utility::isConflictFile(const char *name)
bool Utility::shouldUploadConflictFiles() bool Utility::shouldUploadConflictFiles()
{ {
static bool uploadConflictFiles = qEnvironmentVariableIntValue("OWNCLOUD_UPLOAD_CONFLICT_FILES") != 0; static bool uploadConflictFiles = qgetenv("OWNCLOUD_UPLOAD_CONFLICT_FILES").toInt() != 0;
return uploadConflictFiles; return uploadConflictFiles;
} }

View File

@@ -58,7 +58,7 @@ bool hasLaunchOnStartup_private(const QString &)
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i);
CFURLRef itemUrlRef = NULL; CFURLRef itemUrlRef = NULL;
if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr && itemUrlRef) { if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) {
CFStringRef itemUrlString = CFURLGetString(itemUrlRef); CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) {
returnValue = true; returnValue = true;
@@ -100,7 +100,7 @@ void setLaunchOnStartup_private(const QString &appName, const QString &guiName,
LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i); LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(itemsArray, i);
CFURLRef itemUrlRef = NULL; CFURLRef itemUrlRef = NULL;
if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr && itemUrlRef) { if (LSSharedFileListItemResolve(item, 0, &itemUrlRef, NULL) == noErr) {
CFStringRef itemUrlString = CFURLGetString(itemUrlRef); CFStringRef itemUrlString = CFURLGetString(itemUrlRef);
if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) { if (CFStringCompare(itemUrlString, appUrlRefString, 0) == kCFCompareEqualTo) {
LSSharedFileListItemRemove(loginItems, item); // remove it! LSSharedFileListItemRemove(loginItems, item); // remove it!

View File

@@ -108,8 +108,7 @@ enum csync_status_codes_e {
CSYNC_STATUS_INDIVIDUAL_STAT_FAILED, CSYNC_STATUS_INDIVIDUAL_STAT_FAILED,
CSYNC_STATUS_FORBIDDEN, CSYNC_STATUS_FORBIDDEN,
CSYNC_STATUS_INDIVIDUAL_TOO_DEEP, CSYNC_STATUS_INDIVIDUAL_TOO_DEEP,
CSYNC_STATUS_INDIVIDUAL_IS_CONFLICT_FILE, CSYNC_STATUS_INDIVIDUAL_IS_CONFLICT_FILE
CSYNC_STATUS_INDIVIDUAL_CANNOT_ENCODE
}; };
typedef enum csync_status_codes_e CSYNC_STATUS; typedef enum csync_status_codes_e CSYNC_STATUS;

View File

@@ -33,8 +33,7 @@ enum csync_exclude_type_e {
CSYNC_FILE_EXCLUDE_LONG_FILENAME, CSYNC_FILE_EXCLUDE_LONG_FILENAME,
CSYNC_FILE_EXCLUDE_HIDDEN, CSYNC_FILE_EXCLUDE_HIDDEN,
CSYNC_FILE_EXCLUDE_STAT_FAILED, CSYNC_FILE_EXCLUDE_STAT_FAILED,
CSYNC_FILE_EXCLUDE_CONFLICT, CSYNC_FILE_EXCLUDE_CONFLICT
CSYNC_FILE_EXCLUDE_CANNOT_ENCODE
}; };
typedef enum csync_exclude_type_e CSYNC_EXCLUDE_TYPE; typedef enum csync_exclude_type_e CSYNC_EXCLUDE_TYPE;

View File

@@ -63,6 +63,18 @@ static csync_file_stat_t *_csync_check_ignored(csync_s::FileMap *tree, const Byt
} }
} }
/* Returns true if we're reasonably certain that hash equality
* for the header means content equality.
*
* Cryptographic safety is not required - this is mainly
* intended to rule out checksums like Adler32 that are not intended for
* hashing and have high likelihood of collision with particular inputs.
*/
static bool _csync_is_collision_safe_hash(const char *checksum_header)
{
return strncmp(checksum_header, "SHA1:", 5) == 0
|| strncmp(checksum_header, "MD5:", 4) == 0;
}
/** /**
* The main function in the reconcile pass. * The main function in the reconcile pass.
@@ -92,17 +104,14 @@ static csync_file_stat_t *_csync_check_ignored(csync_s::FileMap *tree, const Byt
* source and the destination, have been changed, the newer file wins. * source and the destination, have been changed, the newer file wins.
*/ */
static int _csync_merge_algorithm_visitor(csync_file_stat_t *cur, CSYNC * ctx) { static int _csync_merge_algorithm_visitor(csync_file_stat_t *cur, CSYNC * ctx) {
csync_s::FileMap *our_tree = nullptr;
csync_s::FileMap *other_tree = nullptr; csync_s::FileMap *other_tree = nullptr;
/* we need the opposite tree! */ /* we need the opposite tree! */
switch (ctx->current) { switch (ctx->current) {
case LOCAL_REPLICA: case LOCAL_REPLICA:
our_tree = &ctx->local.files;
other_tree = &ctx->remote.files; other_tree = &ctx->remote.files;
break; break;
case REMOTE_REPLICA: case REMOTE_REPLICA:
our_tree = &ctx->remote.files;
other_tree = &ctx->local.files; other_tree = &ctx->local.files;
break; break;
default: default:
@@ -143,51 +152,40 @@ static int _csync_merge_algorithm_visitor(csync_file_stat_t *cur, CSYNC * ctx) {
cur->instruction = CSYNC_INSTRUCTION_REMOVE; cur->instruction = CSYNC_INSTRUCTION_REMOVE;
break; break;
case CSYNC_INSTRUCTION_EVAL_RENAME: { case CSYNC_INSTRUCTION_EVAL_RENAME: {
// By default, the EVAL_RENAME decays into a NEW OCC::SyncJournalFileRecord base;
cur->instruction = CSYNC_INSTRUCTION_NEW; if(ctx->current == LOCAL_REPLICA ) {
/* use the old name to find the "other" node */
bool processedRename = false; ctx->statedb->getFileRecordByInode(cur->inode, &base);
auto renameCandidateProcessing = [&](const OCC::SyncJournalFileRecord &base) { qCDebug(lcReconcile, "Finding opposite temp through inode %" PRIu64 ": %s",
if (processedRename) cur->inode, base.isValid() ? "true":"false");
return; } else {
if (!base.isValid()) ASSERT( ctx->current == REMOTE_REPLICA );
return; ctx->statedb->getFileRecordByFileId(cur->file_id, &base);
qCDebug(lcReconcile, "Finding opposite temp through file ID %s: %s",
cur->file_id.constData(), base.isValid() ? "true":"false");
}
if( base.isValid() ) {
/* First, check that the file is NOT in our tree (another file with the same name was added) */ /* First, check that the file is NOT in our tree (another file with the same name was added) */
if (our_tree->findFile(base._path)) { csync_s::FileMap *our_tree = ctx->current == REMOTE_REPLICA ? &ctx->remote.files : &ctx->local.files;
qCDebug(lcReconcile, "Origin found in our tree : %s", base._path.constData()); if (our_tree->findFile(base._path)) {
qCDebug(lcReconcile, "Origin found in our tree : %s", base._path.constData());
} else { } else {
/* Find the potential rename source file in the other tree. /* Find the temporar file in the other tree.
* If the renamed file could not be found in the opposite tree, that is because it * If the renamed file could not be found in the opposite tree, that is because it
* is not longer existing there, maybe because it was renamed or deleted. * is not longer existing there, maybe because it was renamed or deleted.
* The journal is cleaned up later after propagation. * The journal is cleaned up later after propagation.
*/ */
other = other_tree->findFile(base._path); other = other_tree->findFile(base._path);
qCDebug(lcReconcile, "Rename origin in other tree (%s) %s", qCDebug(lcReconcile, "Temporary opposite (%s) %s",
base._path.constData(), other ? "found" : "not found"); base._path.constData() , other ? "found": "not found" );
} }
if(!other) { if(!other) {
// Stick with the NEW cur->instruction = CSYNC_INSTRUCTION_NEW;
return; } else if (other->instruction == CSYNC_INSTRUCTION_NONE
} else if (other->instruction == CSYNC_INSTRUCTION_RENAME) { || other->instruction == CSYNC_INSTRUCTION_UPDATE_METADATA
// Some other EVAL_RENAME already claimed other. || cur->type == CSYNC_FTW_TYPE_DIR) {
// We do nothing: maybe a different candidate for
// other is found as well?
qCDebug(lcReconcile, "Other has already been renamed to %s",
other->rename_path.constData());
} else if (cur->type == CSYNC_FTW_TYPE_DIR
// The local replica is reconciled first, so the remote tree would
// have either NONE or UPDATE_METADATA if the remote file is safe to
// move.
// In the remote replica, REMOVE is also valid (local has already
// been reconciled). NONE can still happen if the whole parent dir
// was set to REMOVE by the local reconcile.
|| other->instruction == CSYNC_INSTRUCTION_NONE
|| other->instruction == CSYNC_INSTRUCTION_UPDATE_METADATA
|| other->instruction == CSYNC_INSTRUCTION_REMOVE) {
qCDebug(lcReconcile, "Switching %s to RENAME to %s",
other->path.constData(), cur->path.constData());
other->instruction = CSYNC_INSTRUCTION_RENAME; other->instruction = CSYNC_INSTRUCTION_RENAME;
other->rename_path = cur->path; other->rename_path = cur->path;
if( !cur->file_id.isEmpty() ) { if( !cur->file_id.isEmpty() ) {
@@ -195,44 +193,24 @@ static int _csync_merge_algorithm_visitor(csync_file_stat_t *cur, CSYNC * ctx) {
} }
other->inode = cur->inode; other->inode = cur->inode;
cur->instruction = CSYNC_INSTRUCTION_NONE; cur->instruction = CSYNC_INSTRUCTION_NONE;
// We have consumed 'other': exit this loop to not consume another one. } else if (other->instruction == CSYNC_INSTRUCTION_REMOVE) {
processedRename = true; other->instruction = CSYNC_INSTRUCTION_RENAME;
} else if (our_tree->findFile(csync_rename_adjust_path(ctx, other->path)) == cur) { other->rename_path = cur->path;
// If we're here, that means that the other side's reconcile will be able
// to work against cur: The filename itself didn't change, only a parent
// directory was renamed! In that case it's safe to ignore the rename
// since the parent directory rename will already deal with it.
// Local: The remote reconcile will be able to deal with this. if( !cur->file_id.isEmpty() ) {
// Remote: The local replica has already dealt with this. other->file_id = cur->file_id;
// See the EVAL_RENAME case when other was found directly. }
qCDebug(lcReconcile, "File in a renamed directory, other side's instruction: %d", other->inode = cur->inode;
other->instruction);
cur->instruction = CSYNC_INSTRUCTION_NONE; cur->instruction = CSYNC_INSTRUCTION_NONE;
} else if (other->instruction == CSYNC_INSTRUCTION_NEW) {
qCDebug(lcReconcile, "OOOO=> NEW detected in other tree!");
cur->instruction = CSYNC_INSTRUCTION_CONFLICT;
} else { } else {
// This can, for instance, happen when there was a local change in other assert(other->type != CSYNC_FTW_TYPE_DIR);
// and the instruction in the local tree is NEW while cur has EVAL_RENAME cur->instruction = CSYNC_INSTRUCTION_NONE;
// due to a remote move of the same file. In these scenarios we just other->instruction = CSYNC_INSTRUCTION_SYNC;
// want the instruction to stay NEW.
qCDebug(lcReconcile, "Other already has instruction %d",
other->instruction);
} }
};
if (ctx->current == LOCAL_REPLICA) {
/* use the old name to find the "other" node */
OCC::SyncJournalFileRecord base;
qCDebug(lcReconcile, "Finding rename origin through inode %" PRIu64 "",
cur->inode);
ctx->statedb->getFileRecordByInode(cur->inode, &base);
renameCandidateProcessing(base);
} else {
ASSERT(ctx->current == REMOTE_REPLICA);
qCDebug(lcReconcile, "Finding rename origin through file ID %s",
cur->file_id.constData());
ctx->statedb->getFileRecordsByFileId(cur->file_id, renameCandidateProcessing);
} }
break; break;
} }
default: default:
@@ -285,14 +263,14 @@ static int _csync_merge_algorithm_visitor(csync_file_stat_t *cur, CSYNC * ctx) {
// //
// In older client versions we always treated these cases as a // In older client versions we always treated these cases as a
// non-conflict. This behavior is preserved in case the server // non-conflict. This behavior is preserved in case the server
// doesn't provide a content checksum. // doesn't provide a suitable content hash.
// //
// When it does have one, however, we do create a job, but the job // When it does have one, however, we do create a job, but the job
// will compare hashes and avoid the download if possible. // will compare hashes and avoid the download if they are equal.
QByteArray remoteChecksumHeader = const char *remoteChecksumHeader =
(ctx->current == REMOTE_REPLICA ? cur->checksumHeader : other->checksumHeader); (ctx->current == REMOTE_REPLICA ? cur->checksumHeader : other->checksumHeader);
if (!remoteChecksumHeader.isEmpty()) { if (remoteChecksumHeader) {
is_conflict = true; is_conflict |= _csync_is_collision_safe_hash(remoteChecksumHeader);
} }
// SO: If there is no checksum, we can have !is_conflict here // SO: If there is no checksum, we can have !is_conflict here
@@ -332,19 +310,10 @@ static int _csync_merge_algorithm_visitor(csync_file_stat_t *cur, CSYNC * ctx) {
break; break;
case CSYNC_INSTRUCTION_IGNORE: case CSYNC_INSTRUCTION_IGNORE:
cur->instruction = CSYNC_INSTRUCTION_IGNORE; cur->instruction = CSYNC_INSTRUCTION_IGNORE;
break; break;
default: default:
break; break;
} }
// Ensure we're not leaving discovery-only instructions
// in place. This can happen, for instance, when other's
// instruction is EVAL_RENAME because the parent dir was renamed.
// NEW is safer than EVAL because it will end up with
// propagation unless it's changed by something, and EVAL and
// NEW are treated equivalently during reconcile.
if (cur->instruction == CSYNC_INSTRUCTION_EVAL)
cur->instruction = CSYNC_INSTRUCTION_NEW;
break;
default: default:
break; break;
} }

View File

@@ -46,8 +46,6 @@
#include "common/utility.h" #include "common/utility.h"
#include "common/asserts.h" #include "common/asserts.h"
#include <QtCore/QTextCodec>
// Needed for PRIu64 on MinGW in C++ mode. // Needed for PRIu64 on MinGW in C++ mode.
#define __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS
#include <inttypes.h> #include <inttypes.h>
@@ -150,14 +148,6 @@ static int _csync_detect_update(CSYNC *ctx, std::unique_ptr<csync_file_stat_t> f
} }
} }
if (ctx->current == REMOTE_REPLICA && QTextCodec::codecForLocale()->mibEnum() != 106) {
/* If the locale codec is not UTF-8, we must check that the filename from the server can
* be encoded in the local file system. */
if (!QTextCodec::codecForLocale()->canEncode(QString::fromUtf8(fs->path))) {
excluded = CSYNC_FILE_EXCLUDE_CANNOT_ENCODE;
}
}
if (fs->type == CSYNC_FTW_TYPE_FILE ) { if (fs->type == CSYNC_FTW_TYPE_FILE ) {
if (fs->modtime == 0) { if (fs->modtime == 0) {
qCDebug(lcUpdate, "file: %s - mtime is zero!", fs->path.constData()); qCDebug(lcUpdate, "file: %s - mtime is zero!", fs->path.constData());
@@ -275,8 +265,8 @@ static int _csync_detect_update(CSYNC *ctx, std::unique_ptr<csync_file_stat_t> f
fs->instruction = CSYNC_INSTRUCTION_NEW; fs->instruction = CSYNC_INSTRUCTION_NEW;
bool isRename = bool isRename =
base.isValid() && base._type == fs->type base.isValid() && base._inode == fs->inode && base._type == fs->type
&& ((base._modtime == fs->modtime && base._fileSize == fs->size) || fs->type == CSYNC_FTW_TYPE_DIR) && (base._modtime == fs->modtime || fs->type == CSYNC_FTW_TYPE_DIR)
#ifdef NO_RENAME_EXTENSION #ifdef NO_RENAME_EXTENSION
&& _csync_sameextension(base._path, fs->path) && _csync_sameextension(base._path, fs->path)
#endif #endif
@@ -307,60 +297,41 @@ static int _csync_detect_update(CSYNC *ctx, std::unique_ptr<csync_file_stat_t> f
} else { } else {
/* Remote Replica Rename check */ /* Remote Replica Rename check */
fs->instruction = CSYNC_INSTRUCTION_NEW; OCC::SyncJournalFileRecord base;
if(!ctx->statedb->getFileRecordByFileId(fs->file_id, &base)) {
bool done = false;
auto renameCandidateProcessing = [&](const OCC::SyncJournalFileRecord &base) {
if (done)
return;
if (!base.isValid())
return;
// Some things prohibit rename detection entirely.
// Since we don't do the same checks again in reconcile, we can't
// just skip the candidate, but have to give up completely.
if (base._type != fs->type) {
qCWarning(lcUpdate, "file types different, not a rename");
done = true;
return;
}
if (fs->type != CSYNC_FTW_TYPE_DIR && base._etag != fs->etag) {
/* File with different etag, don't do a rename, but download the file again */
qCWarning(lcUpdate, "file etag different, not a rename");
done = true;
return;
}
// Record directory renames
if (fs->type == CSYNC_FTW_TYPE_DIR) {
// If the same folder was already renamed by a different entry,
// skip to the next candidate
if (ctx->renames.folder_renamed_to.count(base._path) > 0) {
qCWarning(lcUpdate, "folder already has a rename entry, skipping");
return;
}
csync_rename_record(ctx, base._path, fs->path);
}
qCDebug(lcUpdate, "remote rename detected based on fileid %s --> %s", base._path.constData(), fs->path.constData());
fs->instruction = CSYNC_INSTRUCTION_EVAL_RENAME;
done = true;
};
if (!ctx->statedb->getFileRecordsByFileId(fs->file_id, renameCandidateProcessing)) {
ctx->status_code = CSYNC_STATUS_UNSUCCESSFUL; ctx->status_code = CSYNC_STATUS_UNSUCCESSFUL;
return -1; return -1;
} }
if (base.isValid()) { /* tmp existing at all */
if (fs->instruction == CSYNC_INSTRUCTION_NEW if (base._type != fs->type) {
&& fs->type == CSYNC_FTW_TYPE_DIR qCWarning(lcUpdate, "file types different is not!");
&& ctx->current == REMOTE_REPLICA fs->instruction = CSYNC_INSTRUCTION_NEW;
&& ctx->callbacks.checkSelectiveSyncNewFolderHook) { goto out;
if (ctx->callbacks.checkSelectiveSyncNewFolderHook(ctx->callbacks.update_callback_userdata, fs->path, fs->remotePerm)) {
return 1;
} }
qCDebug(lcUpdate, "remote rename detected based on fileid %s --> %s", base._path.constData(), fs->path.constData());
fs->instruction = CSYNC_INSTRUCTION_EVAL_RENAME;
if (fs->type == CSYNC_FTW_TYPE_DIR) {
csync_rename_record(ctx, base._path, fs->path);
} else {
if( base._etag != fs->etag ) {
/* CSYNC_LOG(CSYNC_LOG_PRIORITY_DEBUG, "ETags are different!"); */
/* File with different etag, don't do a rename, but download the file again */
fs->instruction = CSYNC_INSTRUCTION_NEW;
}
}
goto out;
} else {
/* file not found in statedb */
fs->instruction = CSYNC_INSTRUCTION_NEW;
if (fs->type == CSYNC_FTW_TYPE_DIR && ctx->current == REMOTE_REPLICA && ctx->callbacks.checkSelectiveSyncNewFolderHook) {
if (ctx->callbacks.checkSelectiveSyncNewFolderHook(ctx->callbacks.update_callback_userdata, fs->path, fs->remotePerm)) {
return 1;
}
}
goto out;
} }
goto out;
} }
} }
@@ -385,8 +356,6 @@ out:
fs->error_status = CSYNC_STATUS_INDIVIDUAL_STAT_FAILED; fs->error_status = CSYNC_STATUS_INDIVIDUAL_STAT_FAILED;
} else if (excluded == CSYNC_FILE_EXCLUDE_CONFLICT) { } else if (excluded == CSYNC_FILE_EXCLUDE_CONFLICT) {
fs->error_status = CSYNC_STATUS_INDIVIDUAL_IS_CONFLICT_FILE; fs->error_status = CSYNC_STATUS_INDIVIDUAL_IS_CONFLICT_FILE;
} else if (excluded == CSYNC_FILE_EXCLUDE_CANNOT_ENCODE) {
fs->error_status = CSYNC_STATUS_INDIVIDUAL_CANNOT_ENCODE;
} }
} }
} }
@@ -647,7 +616,7 @@ int csync_ftw(CSYNC *ctx, const char *uri, csync_walker_fn fn,
* local stat function. * local stat function.
*/ */
if( filename[0] == '.' ) { if( filename[0] == '.' ) {
if (filename != ".sys.admin#recall#") { /* recall file shall not be ignored (#4420) */ if (filename == ".sys.admin#recall#") { /* recall file shall not be ignored (#4420) */
dirent->is_hidden = true; dirent->is_hidden = true;
} }
} }

View File

@@ -211,10 +211,3 @@ time_t oc_httpdate_parse( const char *date ) {
result = timegm(&gmt); result = timegm(&gmt);
return result; return result;
} }
bool csync_is_collision_safe_hash(const QByteArray &checksum_header)
{
return checksum_header.startsWith("SHA1:")
|| checksum_header.startsWith("MD5:");
}

View File

@@ -31,14 +31,4 @@ const char OCSYNC_EXPORT *csync_instruction_str(enum csync_instructions_e instr)
void OCSYNC_EXPORT csync_memstat_check(void); void OCSYNC_EXPORT csync_memstat_check(void);
bool OCSYNC_EXPORT csync_file_locked_or_open( const char *dir, const char *fname); bool OCSYNC_EXPORT csync_file_locked_or_open( const char *dir, const char *fname);
/* Returns true if we're reasonably certain that hash equality
* for the header means content equality.
*
* Cryptographic safety is not required - this is mainly
* intended to rule out checksums like Adler32 that are not intended for
* hashing and have high likelihood of collision with particular inputs.
*/
bool OCSYNC_EXPORT csync_is_collision_safe_hash(const QByteArray &checksum_header);
#endif /* _CSYNC_UTIL_H */ #endif /* _CSYNC_UTIL_H */

View File

@@ -129,7 +129,6 @@ set(updater_SRCS
IF( APPLE ) IF( APPLE )
list(APPEND client_SRCS cocoainitializer_mac.mm) list(APPEND client_SRCS cocoainitializer_mac.mm)
list(APPEND client_SRCS settingsdialogmac.cpp) list(APPEND client_SRCS settingsdialogmac.cpp)
list(REMOVE_ITEM client_SRCS settingsdialog.cpp)
list(APPEND client_SRCS socketapisocket_mac.mm) list(APPEND client_SRCS socketapisocket_mac.mm)
list(APPEND client_SRCS systray.mm) list(APPEND client_SRCS systray.mm)
@@ -243,9 +242,8 @@ if (NOT NO_SHIBBOLETH)
endif() endif()
if(UNIX AND NOT APPLE) if(UNIX AND NOT APPLE)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fPIE") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pie -fPIE")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIE") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pie -fPIE")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pie")
endif() endif()
if(NOT BUILD_OWNCLOUD_OSX_BUNDLE) if(NOT BUILD_OWNCLOUD_OSX_BUNDLE)

View File

@@ -263,6 +263,7 @@ void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos)
} }
if (_model->classify(index) == FolderStatusModel::SubFolder) { if (_model->classify(index) == FolderStatusModel::SubFolder) {
QTreeView *tv = ui->_folderList;
QMenu *menu = new QMenu(tv); QMenu *menu = new QMenu(tv);
menu->setAttribute(Qt::WA_DeleteOnClose); menu->setAttribute(Qt::WA_DeleteOnClose);
@@ -274,7 +275,8 @@ void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos)
ac->setEnabled(false); ac->setEnabled(false);
} }
menu->popup(tv->mapToGlobal(pos)); menu->exec(QCursor::pos());
return; return;
} }
@@ -289,7 +291,6 @@ void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos)
auto folderMan = FolderMan::instance(); auto folderMan = FolderMan::instance();
QMenu *menu = new QMenu(tv); QMenu *menu = new QMenu(tv);
menu->setAttribute(Qt::WA_DeleteOnClose); menu->setAttribute(Qt::WA_DeleteOnClose);
QAction *ac = menu->addAction(tr("Open folder")); QAction *ac = menu->addAction(tr("Open folder"));
@@ -315,7 +316,7 @@ void AccountSettings::slotCustomContextMenuRequested(const QPoint &pos)
ac = menu->addAction(tr("Remove folder sync connection")); ac = menu->addAction(tr("Remove folder sync connection"));
connect(ac, &QAction::triggered, this, &AccountSettings::slotRemoveCurrentFolder); connect(ac, &QAction::triggered, this, &AccountSettings::slotRemoveCurrentFolder);
menu->popup(tv->mapToGlobal(pos)); menu->exec(tv->mapToGlobal(pos));
} }
void AccountSettings::slotFolderListClicked(const QModelIndex &indx) void AccountSettings::slotFolderListClicked(const QModelIndex &indx)
@@ -637,11 +638,7 @@ void AccountSettings::slotAccountStateChanged()
Utility::escape(safeUrl.toString())); Utility::escape(safeUrl.toString()));
QString serverWithUser = server; QString serverWithUser = server;
if (AbstractCredentials *cred = account->credentials()) { if (AbstractCredentials *cred = account->credentials()) {
QString user = account->davDisplayName(); serverWithUser = tr("%1 as <i>%2</i>").arg(server, Utility::escape(cred->user()));
if (user.isEmpty()) {
user = cred->user();
}
serverWithUser = tr("%1 as <i>%2</i>").arg(server, Utility::escape(user));
} }
if (state == AccountState::Connected) { if (state == AccountState::Connected) {

View File

@@ -361,4 +361,23 @@ std::unique_ptr<QSettings> AccountState::settings()
return s; return s;
} }
QString AccountState::shortDisplayNameForSettings(int width) const
{
QString user = account()->credentials()->user();
QString host = account()->url().host();
int port = account()->url().port();
if (port > 0 && port != 80 && port != 443) {
host.append(QLatin1Char(':'));
host.append(QString::number(port));
}
if (width > 0) {
QFont f;
QFontMetrics fm(f);
host = fm.elidedText(host, Qt::ElideMiddle, width);
user = fm.elidedText(user, Qt::ElideRight, width);
}
return user + QLatin1String("\n") + host;
}
} // namespace OCC } // namespace OCC

View File

@@ -113,6 +113,11 @@ public:
/** Returns a new settings object for this account, already in the right groups. */ /** Returns a new settings object for this account, already in the right groups. */
std::unique_ptr<QSettings> settings(); std::unique_ptr<QSettings> settings();
/** display name with two lines that is displayed in the settings
* If width is bigger than 0, the string will be ellided so it does not exceed that width
*/
QString shortDisplayNameForSettings(int width = 0) const;
/** Mark the timestamp when the last successful ETag check happened for /** Mark the timestamp when the last successful ETag check happened for
* this account. * this account.
* The checkConnectivity() method uses the timestamp to save a call to * The checkConnectivity() method uses the timestamp to save a call to

View File

@@ -30,21 +30,19 @@ using namespace QKeychain;
namespace OCC { namespace OCC {
Q_LOGGING_CATEGORY(lcHttpCredentialsGui, "sync.credentials.http.gui", QtInfoMsg)
void HttpCredentialsGui::askFromUser() void HttpCredentialsGui::askFromUser()
{ {
// This function can be called from AccountState::slotInvalidCredentials, // Unfortunately there's a bug that doesn't allow us to send the "is this
// which (indirectly, through HttpCredentials::invalidateToken) schedules // OAuth2 or Basic auth?" GET request directly. Scheduling it for the event
// a cache wipe of the qnam. We can only execute a network job again once // loop works though. See #5989.
// the cache has been cleared, otherwise we'd interfere with the job. QMetaObject::invokeMethod(this, "askFromUserAsync", Qt::QueuedConnection);
QTimer::singleShot(100, this, &HttpCredentialsGui::askFromUserAsync);
} }
void HttpCredentialsGui::askFromUserAsync() void HttpCredentialsGui::askFromUserAsync()
{ {
// First, we will check what kind of auth we need. // First, we will check what kind of auth we need.
auto job = new DetermineAuthTypeJob(_account->sharedFromThis(), this); auto job = new DetermineAuthTypeJob(_account->sharedFromThis(), this);
job->setTimeout(30 * 1000);
QObject::connect(job, &DetermineAuthTypeJob::authType, this, [this](DetermineAuthTypeJob::AuthType type) { QObject::connect(job, &DetermineAuthTypeJob::authType, this, [this](DetermineAuthTypeJob::AuthType type) {
if (type == DetermineAuthTypeJob::OAuth) { if (type == DetermineAuthTypeJob::OAuth) {
_asyncAuth.reset(new OAuth(_account, this)); _asyncAuth.reset(new OAuth(_account, this));
@@ -60,8 +58,7 @@ void HttpCredentialsGui::askFromUserAsync()
// We will re-enter the event loop, so better wait the next iteration // We will re-enter the event loop, so better wait the next iteration
QMetaObject::invokeMethod(this, "showDialog", Qt::QueuedConnection); QMetaObject::invokeMethod(this, "showDialog", Qt::QueuedConnection);
} else { } else {
// Shibboleth? // Network error? Unsupported auth type?
qCWarning(lcHttpCredentialsGui) << "Bad http auth type:" << type;
emit asked(); emit asked();
} }
}); });

View File

@@ -60,12 +60,12 @@ public:
private slots: private slots:
void asyncAuthResult(OAuth::Result, const QString &user, const QString &accessToken, const QString &refreshToken); void asyncAuthResult(OAuth::Result, const QString &user, const QString &accessToken, const QString &refreshToken);
void showDialog(); void showDialog();
void askFromUserAsync();
signals: signals:
void authorisationLinkChanged(); void authorisationLinkChanged();
private: private:
Q_INVOKABLE void askFromUserAsync();
QScopedPointer<OAuth, QScopedPointerObjectDeleteLater<OAuth>> _asyncAuth; QScopedPointer<OAuth, QScopedPointerObjectDeleteLater<OAuth>> _asyncAuth;
}; };

View File

@@ -43,7 +43,7 @@ public:
UserAgentWebPage(QObject *parent) UserAgentWebPage(QObject *parent)
: QWebPage(parent) : QWebPage(parent)
{ {
if (!qEnvironmentVariableIsEmpty("OWNCLOUD_SHIBBOLETH_DEBUG")) { if (!qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty()) {
settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true); settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
} }
} }
@@ -83,7 +83,7 @@ ShibbolethWebView::ShibbolethWebView(AccountPtr account, QWidget *parent)
setWindowTitle(tr("%1 - Authenticate").arg(Theme::instance()->appNameGUI())); setWindowTitle(tr("%1 - Authenticate").arg(Theme::instance()->appNameGUI()));
// Debug view to display the cipher suite // Debug view to display the cipher suite
if (!qEnvironmentVariableIsEmpty("OWNCLOUD_SHIBBOLETH_DEBUG")) { if (!qgetenv("OWNCLOUD_SHIBBOLETH_DEBUG").isEmpty()) {
// open an additional window to display some cipher debug info // open an additional window to display some cipher debug info
QWebPage *debugPage = new UserAgentWebPage(this); QWebPage *debugPage = new UserAgentWebPage(this);
debugPage->mainFrame()->load(QUrl("https://cc.dcsec.uni-hannover.de/")); debugPage->mainFrame()->load(QUrl("https://cc.dcsec.uni-hannover.de/"));

View File

@@ -23,7 +23,6 @@
#include "creds/shibbolethcredentials.h" #include "creds/shibbolethcredentials.h"
#include "shibboleth/shibbolethuserjob.h" #include "shibboleth/shibbolethuserjob.h"
#include "creds/credentialscommon.h" #include "creds/credentialscommon.h"
#include "creds/httpcredentialsgui.h"
#include "accessmanager.h" #include "accessmanager.h"
#include "account.h" #include "account.h"
@@ -152,31 +151,7 @@ void ShibbolethCredentials::fetchFromKeychainHelper()
void ShibbolethCredentials::askFromUser() void ShibbolethCredentials::askFromUser()
{ {
// First, we do a DetermineAuthTypeJob to make sure that the server is still using shibboleth and did not upgrade to oauth showLoginWindow();
DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_account->sharedFromThis(), this);
connect(job, &DetermineAuthTypeJob::authType, [this, job](DetermineAuthTypeJob::AuthType type) {
if (type == DetermineAuthTypeJob::Shibboleth) {
// Normal case, still shibboleth
showLoginWindow();
} else if (type == DetermineAuthTypeJob::OAuth) {
// Hack: upgrade to oauth
auto newCred = new HttpCredentialsGui;
job->setParent(0);
job->deleteLater();
auto account = this->_account;
auto user = this->_user;
account->setCredentials(newCred); // delete this
account->setCredentialSetting(QLatin1String("user"), user);
newCred->fetchUser();
newCred->askFromUser();
} else {
// Basic auth or unkown. Since it may be unkown it might be a temporary failure, don't replace the credentials here
// Still show the login window in that case not to break the flow.
showLoginWindow();
}
});
job->start();
} }
bool ShibbolethCredentials::stillValid(QNetworkReply *reply) bool ShibbolethCredentials::stillValid(QNetworkReply *reply)

View File

@@ -841,11 +841,6 @@ void Folder::slotTransmissionProgress(const ProgressInfo &pi)
// a item is completed: count the errors and forward to the ProgressDispatcher // a item is completed: count the errors and forward to the ProgressDispatcher
void Folder::slotItemCompleted(const SyncFileItemPtr &item) void Folder::slotItemCompleted(const SyncFileItemPtr &item)
{ {
if (item->_instruction == CSYNC_INSTRUCTION_NONE || item->_instruction == CSYNC_INSTRUCTION_UPDATE_METADATA) {
// We only care about the updates that deserve to be shown in the UI
return;
}
// add new directories or remove gone away dirs to the watcher // add new directories or remove gone away dirs to the watcher
if (item->isDirectory() && item->_instruction == CSYNC_INSTRUCTION_NEW) { if (item->isDirectory() && item->_instruction == CSYNC_INSTRUCTION_NEW) {
FolderMan::instance()->addMonitorPath(alias(), path() + item->_file); FolderMan::instance()->addMonitorPath(alias(), path() + item->_file);

View File

@@ -59,7 +59,7 @@ QSize FolderStatusDelegate::sizeHint(const QStyleOptionViewItem &option,
auto classif = static_cast<const FolderStatusModel *>(index.model())->classify(index); auto classif = static_cast<const FolderStatusModel *>(index.model())->classify(index);
if (classif == FolderStatusModel::AddButton) { if (classif == FolderStatusModel::AddButton) {
const int margins = aliasFm.height(); // same as 2*aliasMargin of paint const int margins = aliasFm.height(); // same as 2*aliasMargin of paint
QFontMetrics fm(qApp->font("QPushButton")); QFontMetrics fm(option.font);
QStyleOptionButton opt; QStyleOptionButton opt;
static_cast<QStyleOption &>(opt) = option; static_cast<QStyleOption &>(opt) = option;
opt.text = addFolderText(); opt.text = addFolderText();
@@ -138,10 +138,7 @@ void FolderStatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &
opt.rect.setWidth(qMin(opt.rect.width(), hint.width())); opt.rect.setWidth(qMin(opt.rect.width(), hint.width()));
opt.rect.adjust(0, aliasMargin, 0, -aliasMargin); opt.rect.adjust(0, aliasMargin, 0, -aliasMargin);
opt.rect = QStyle::visualRect(option.direction, option.rect, opt.rect); opt.rect = QStyle::visualRect(option.direction, option.rect, opt.rect);
painter->save();
painter->setFont(qApp->font("QPushButton"));
QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter, option.widget); QApplication::style()->drawControl(QStyle::CE_PushButton, &opt, painter, option.widget);
painter->restore();
return; return;
} }

View File

@@ -35,7 +35,6 @@
#include <QWizardPage> #include <QWizardPage>
#include <QTreeWidget> #include <QTreeWidget>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QEvent>
#include <stdlib.h> #include <stdlib.h>
@@ -537,11 +536,9 @@ FolderWizard::FolderWizard(AccountPtr account, QWidget *parent)
{ {
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setPage(Page_Source, _folderWizardSourcePage); setPage(Page_Source, _folderWizardSourcePage);
_folderWizardSourcePage->installEventFilter(this);
if (!Theme::instance()->singleSyncFolder()) { if (!Theme::instance()->singleSyncFolder()) {
_folderWizardTargetPage = new FolderWizardRemotePath(account); _folderWizardTargetPage = new FolderWizardRemotePath(account);
setPage(Page_Target, _folderWizardTargetPage); setPage(Page_Target, _folderWizardTargetPage);
_folderWizardTargetPage->installEventFilter(this);
} }
setPage(Page_SelectiveSync, _folderWizardSelectiveSyncPage); setPage(Page_SelectiveSync, _folderWizardSelectiveSyncPage);
@@ -554,25 +551,5 @@ FolderWizard::~FolderWizard()
{ {
} }
bool FolderWizard::eventFilter(QObject *watched, QEvent *event)
{
if (event->type() == QEvent::LayoutRequest) {
// Workaround QTBUG-3396: forces QWizardPrivate::updateLayout()
QTimer::singleShot(0, this, [this] { setTitleFormat(titleFormat()); });
}
return QWizard::eventFilter(watched, event);
}
void FolderWizard::resizeEvent(QResizeEvent *event)
{
QWizard::resizeEvent(event);
// workaround for QTBUG-22819: when the error label word wrap, the minimum height is not adjusted
int hfw = currentPage()->heightForWidth(currentPage()->width());
if (currentPage()->height() < hfw) {
currentPage()->setMinimumSize(currentPage()->minimumSizeHint().width(), hfw);
setTitleFormat(titleFormat()); // And another workaround for QTBUG-3396
}
}
} // end namespace } // end namespace

View File

@@ -149,9 +149,6 @@ public:
explicit FolderWizard(AccountPtr account, QWidget *parent = 0); explicit FolderWizard(AccountPtr account, QWidget *parent = 0);
~FolderWizard(); ~FolderWizard();
bool eventFilter(QObject *watched, QEvent *event) override;
void resizeEvent(QResizeEvent *event) override;
private: private:
FolderWizardLocalPath *_folderWizardSourcePage; FolderWizardLocalPath *_folderWizardSourcePage;
FolderWizardRemotePath *_folderWizardTargetPage; FolderWizardRemotePath *_folderWizardTargetPage;

View File

@@ -107,16 +107,6 @@ void IssuesWidget::showEvent(QShowEvent *ev)
{ {
ConfigFile cfg; ConfigFile cfg;
cfg.restoreGeometryHeader(_ui->_treeWidget->header()); cfg.restoreGeometryHeader(_ui->_treeWidget->header());
// Sorting by section was newly enabled. But if we restore the header
// from a state where sorting was disabled, both of these flags will be
// false and sorting will be impossible!
_ui->_treeWidget->header()->setSectionsClickable(true);
_ui->_treeWidget->header()->setSortIndicatorShown(true);
// Switch back to "first important, then by time" ordering
_ui->_treeWidget->sortByColumn(0, Qt::DescendingOrder);
QWidget::showEvent(ev); QWidget::showEvent(ev);
} }
@@ -129,8 +119,6 @@ void IssuesWidget::hideEvent(QHideEvent *ev)
void IssuesWidget::cleanItems(const QString &folder) void IssuesWidget::cleanItems(const QString &folder)
{ {
_ui->_treeWidget->setSortingEnabled(false);
// The issue list is a state, clear it and let the next sync fill it // The issue list is a state, clear it and let the next sync fill it
// with ignored files and propagation errors. // with ignored files and propagation errors.
int itemCnt = _ui->_treeWidget->topLevelItemCount(); int itemCnt = _ui->_treeWidget->topLevelItemCount();
@@ -141,9 +129,6 @@ void IssuesWidget::cleanItems(const QString &folder)
delete item; delete item;
} }
} }
_ui->_treeWidget->setSortingEnabled(true);
// update the tabtext // update the tabtext
emit(issueCountUpdated(_ui->_treeWidget->topLevelItemCount())); emit(issueCountUpdated(_ui->_treeWidget->topLevelItemCount()));
} }
@@ -255,7 +240,7 @@ bool IssuesWidget::shouldBeVisible(QTreeWidgetItem *item, AccountState *filterAc
const QString &filterFolderAlias) const const QString &filterFolderAlias) const
{ {
bool visible = true; bool visible = true;
auto status = item->data(3, Qt::UserRole); auto status = item->data(0, Qt::UserRole);
visible &= (_ui->showIgnores->isChecked() || status != SyncFileItem::FileIgnored); visible &= (_ui->showIgnores->isChecked() || status != SyncFileItem::FileIgnored);
visible &= (_ui->showWarnings->isChecked() visible &= (_ui->showWarnings->isChecked()
|| (status != SyncFileItem::SoftError || (status != SyncFileItem::SoftError
@@ -383,14 +368,13 @@ void IssuesWidget::addError(const QString &folderAlias, const QString &message,
QIcon icon = Theme::instance()->syncStateIcon(SyncResult::Error); QIcon icon = Theme::instance()->syncStateIcon(SyncResult::Error);
QTreeWidgetItem *twitem = new SortedTreeWidgetItem(columns); QTreeWidgetItem *twitem = new QTreeWidgetItem(columns);
twitem->setData(0, Qt::SizeHintRole, QSize(0, ActivityItemDelegate::rowHeight())); twitem->setData(0, Qt::SizeHintRole, QSize(0, ActivityItemDelegate::rowHeight()));
twitem->setData(0, Qt::UserRole, timestamp);
twitem->setIcon(0, icon); twitem->setIcon(0, icon);
twitem->setToolTip(0, longTimeStr); twitem->setToolTip(0, longTimeStr);
twitem->setData(2, Qt::UserRole, folderAlias);
twitem->setToolTip(3, message); twitem->setToolTip(3, message);
twitem->setData(3, Qt::UserRole, SyncFileItem::NormalError); twitem->setData(0, Qt::UserRole, SyncFileItem::NormalError);
twitem->setData(2, Qt::UserRole, folderAlias);
addItem(twitem); addItem(twitem);
addErrorWidget(twitem, message, category); addErrorWidget(twitem, message, category);

View File

@@ -99,9 +99,6 @@
<property name="rootIsDecorated"> <property name="rootIsDecorated">
<bool>false</bool> <bool>false</bool>
</property> </property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="columnCount"> <property name="columnCount">
<number>4</number> <number>4</number>
</property> </property>

View File

@@ -88,7 +88,7 @@ int main(int argc, char **argv)
// check a environment variable for core dumps // check a environment variable for core dumps
#ifdef Q_OS_UNIX #ifdef Q_OS_UNIX
if (!qEnvironmentVariableIsEmpty("OWNCLOUD_CORE_DUMP")) { if (!qgetenv("OWNCLOUD_CORE_DUMP").isEmpty()) {
struct rlimit core_limit; struct rlimit core_limit;
core_limit.rlim_cur = RLIM_INFINITY; core_limit.rlim_cur = RLIM_INFINITY;
core_limit.rlim_max = RLIM_INFINITY; core_limit.rlim_max = RLIM_INFINITY;

View File

@@ -207,23 +207,13 @@ void ownCloudGui::slotComputeOverallSyncStatus()
{ {
bool allSignedOut = true; bool allSignedOut = true;
bool allPaused = true; bool allPaused = true;
bool allDisconnected = true;
QVector<AccountStatePtr> problemAccounts; QVector<AccountStatePtr> problemAccounts;
auto setStatusText = [&](const QString &text) {
// Don't overwrite the status if we're currently syncing
if (FolderMan::instance()->currentSyncFolder())
return;
_actionStatus->setText(text);
};
foreach (auto a, AccountManager::instance()->accounts()) { foreach (auto a, AccountManager::instance()->accounts()) {
if (!a->isSignedOut()) { if (!a->isSignedOut()) {
allSignedOut = false; allSignedOut = false;
} }
if (!a->isConnected()) { if (!a->isConnected()) {
problemAccounts.append(a); problemAccounts.append(a);
} else {
allDisconnected = false;
} }
} }
foreach (Folder *f, FolderMan::instance()->map()) { foreach (Folder *f, FolderMan::instance()->map()) {
@@ -234,11 +224,6 @@ void ownCloudGui::slotComputeOverallSyncStatus()
if (!problemAccounts.empty()) { if (!problemAccounts.empty()) {
_tray->setIcon(Theme::instance()->folderOfflineIcon(true, contextMenuVisible())); _tray->setIcon(Theme::instance()->folderOfflineIcon(true, contextMenuVisible()));
if (allDisconnected) {
setStatusText(tr("Disconnected"));
} else {
setStatusText(tr("Disconnected from some accounts"));
}
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
// Windows has a 128-char tray tooltip length limit. // Windows has a 128-char tray tooltip length limit.
QStringList accountNames; QStringList accountNames;
@@ -265,12 +250,10 @@ void ownCloudGui::slotComputeOverallSyncStatus()
if (allSignedOut) { if (allSignedOut) {
_tray->setIcon(Theme::instance()->folderOfflineIcon(true, contextMenuVisible())); _tray->setIcon(Theme::instance()->folderOfflineIcon(true, contextMenuVisible()));
_tray->setToolTip(tr("Please sign in")); _tray->setToolTip(tr("Please sign in"));
setStatusText(tr("Signed out"));
return; return;
} else if (allPaused) { } else if (allPaused) {
_tray->setIcon(Theme::instance()->syncStateIcon(SyncResult::Paused, true, contextMenuVisible())); _tray->setIcon(Theme::instance()->syncStateIcon(SyncResult::Paused, true, contextMenuVisible()));
_tray->setToolTip(tr("Account synchronization is disabled")); _tray->setToolTip(tr("Account synchronization is disabled"));
setStatusText(tr("Synchronization is paused"));
return; return;
} }
@@ -278,40 +261,34 @@ void ownCloudGui::slotComputeOverallSyncStatus()
QString trayMessage; QString trayMessage;
FolderMan *folderMan = FolderMan::instance(); FolderMan *folderMan = FolderMan::instance();
Folder::Map map = folderMan->map(); Folder::Map map = folderMan->map();
SyncResult::Status overallResult = FolderMan::accountStatus(map.values()).status(); SyncResult overallResult = FolderMan::accountStatus(map.values());
// create the tray blob message, check if we have an defined state // create the tray blob message, check if we have an defined state
if (overallResult != SyncResult::Undefined && map.count() > 0) { if (overallResult.status() != SyncResult::Undefined) {
if (map.count() > 0) {
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
// Windows has a 128-char tray tooltip length limit. // Windows has a 128-char tray tooltip length limit.
trayMessage = folderMan->statusToString(overallResult, false); trayMessage = folderMan->statusToString(overallResult.status(), false);
#else #else
QStringList allStatusStrings; QStringList allStatusStrings;
foreach (Folder *folder, map.values()) { foreach (Folder *folder, map.values()) {
QString folderMessage = folderMan->statusToString(folder->syncResult().status(), folder->syncPaused()); QString folderMessage = folderMan->statusToString(folder->syncResult().status(), folder->syncPaused());
allStatusStrings += tr("Folder %1: %2").arg(folder->shortGuiLocalPath(), folderMessage); allStatusStrings += tr("Folder %1: %2").arg(folder->shortGuiLocalPath(), folderMessage);
} }
trayMessage = allStatusStrings.join(QLatin1String("\n")); trayMessage = allStatusStrings.join(QLatin1String("\n"));
#endif #endif
} else {
trayMessage = tr("No sync folders configured.");
}
QIcon statusIcon = Theme::instance()->syncStateIcon(overallResult, true, contextMenuVisible()); QIcon statusIcon = Theme::instance()->syncStateIcon(overallResult.status(), true, contextMenuVisible());
_tray->setIcon(statusIcon); _tray->setIcon(statusIcon);
_tray->setToolTip(trayMessage); _tray->setToolTip(trayMessage);
if (overallResult == SyncResult::Success || overallResult == SyncResult::Problem) {
setStatusText(tr("Up to date"));
} else if (overallResult == SyncResult::Paused) {
setStatusText(tr("Synchronization is paused"));
} else {
setStatusText(tr("Error during synchronization"));
}
} else { } else {
if (overallResult == SyncResult::Undefined) // undefined because there are no folders.
overallResult = SyncResult::Problem; QIcon icon = Theme::instance()->syncStateIcon(SyncResult::Problem, true, contextMenuVisible());
QIcon icon = Theme::instance()->syncStateIcon(overallResult, true, contextMenuVisible());
_tray->setIcon(icon); _tray->setIcon(icon);
_tray->setToolTip(tr("There are no sync folders configured.")); _tray->setToolTip(tr("There are no sync folders configured."));
setStatusText(tr("No sync folders configured"));
} }
} }
@@ -349,7 +326,7 @@ void ownCloudGui::addAccountContextMenu(AccountStatePtr accountState, QMenu *men
menu->addAction(tr("Managed Folders:"))->setDisabled(true); menu->addAction(tr("Managed Folders:"))->setDisabled(true);
} }
QAction *action = menu->addAction(tr("Open folder '%1'").arg(folder->shortGuiLocalPath())); QAction *action = new QAction(tr("Open folder '%1'").arg(folder->shortGuiLocalPath()), menu);
auto alias = folder->alias(); auto alias = folder->alias();
connect(action, &QAction::triggered, this, [this, alias] { this->slotFolderOpenAction(alias); }); connect(action, &QAction::triggered, this, [this, alias] { this->slotFolderOpenAction(alias); });
} }
@@ -573,13 +550,11 @@ void ownCloudGui::updateContextMenu()
_contextMenu->addSeparator(); _contextMenu->addSeparator();
_contextMenu->addAction(_actionStatus);
if (isConfigured && atLeastOneConnected) { if (isConfigured && atLeastOneConnected) {
_contextMenu->addAction(_actionStatus);
_contextMenu->addMenu(_recentActionsMenu); _contextMenu->addMenu(_recentActionsMenu);
_contextMenu->addSeparator();
} }
_contextMenu->addSeparator();
if (accountList.isEmpty()) { if (accountList.isEmpty()) {
_contextMenu->addAction(_actionNewAccountWizard); _contextMenu->addAction(_actionNewAccountWizard);
} }
@@ -767,7 +742,7 @@ void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo &
.arg(progress._currentDiscoveredFolder)); .arg(progress._currentDiscoveredFolder));
} }
} else if (progress.status() == ProgressInfo::Done) { } else if (progress.status() == ProgressInfo::Done) {
QTimer::singleShot(2000, this, &ownCloudGui::slotComputeOverallSyncStatus); QTimer::singleShot(2000, this, &ownCloudGui::slotDisplayIdle);
} }
if (progress.status() != ProgressInfo::Propagation) { if (progress.status() != ProgressInfo::Propagation) {
return; return;
@@ -837,6 +812,11 @@ void ownCloudGui::slotUpdateProgress(const QString &folder, const ProgressInfo &
} }
} }
void ownCloudGui::slotDisplayIdle()
{
_actionStatus->setText(tr("Up to date"));
}
void ownCloudGui::slotLogin() void ownCloudGui::slotLogin()
{ {
if (auto account = qvariant_cast<AccountStatePtr>(sender()->property(propertyAccountC))) { if (auto account = qvariant_cast<AccountStatePtr>(sender()->property(propertyAccountC))) {

View File

@@ -98,6 +98,7 @@ public slots:
void slotRemoveDestroyedShareDialogs(); void slotRemoveDestroyedShareDialogs();
private slots: private slots:
void slotDisplayIdle();
void slotLogin(); void slotLogin();
void slotLogout(); void slotLogout();
void slotUnpauseAllFolders(); void slotUnpauseAllFolders();

View File

@@ -18,7 +18,6 @@
#include <QProcess> #include <QProcess>
#include <QMessageBox> #include <QMessageBox>
#include <QDesktopServices> #include <QDesktopServices>
#include <QApplication>
#include "wizard/owncloudwizardcommon.h" #include "wizard/owncloudwizardcommon.h"
#include "wizard/owncloudwizard.h" #include "wizard/owncloudwizard.h"
@@ -46,7 +45,7 @@ OwncloudSetupWizard::OwncloudSetupWizard(QObject *parent)
, _remoteFolder() , _remoteFolder()
{ {
connect(_ocWizard, &OwncloudWizard::determineAuthType, connect(_ocWizard, &OwncloudWizard::determineAuthType,
this, &OwncloudSetupWizard::slotCheckServer); this, &OwncloudSetupWizard::slotDetermineAuthType);
connect(_ocWizard, &OwncloudWizard::connectToOCUrl, connect(_ocWizard, &OwncloudWizard::connectToOCUrl,
this, &OwncloudSetupWizard::slotConnectToOCUrl); this, &OwncloudSetupWizard::slotConnectToOCUrl);
connect(_ocWizard, &OwncloudWizard::createLocalAndRemoteFolders, connect(_ocWizard, &OwncloudWizard::createLocalAndRemoteFolders,
@@ -70,7 +69,6 @@ static QPointer<OwncloudSetupWizard> wiz = 0;
void OwncloudSetupWizard::runWizard(QObject *obj, const char *amember, QWidget *parent) void OwncloudSetupWizard::runWizard(QObject *obj, const char *amember, QWidget *parent)
{ {
if (!wiz.isNull()) { if (!wiz.isNull()) {
bringWizardToFrontIfVisible();
return; return;
} }
@@ -86,17 +84,6 @@ bool OwncloudSetupWizard::bringWizardToFrontIfVisible()
return false; return false;
} }
if (wiz->_ocWizard->currentId() == WizardCommon::Page_ShibbolethCreds) {
// Try to find if there is a browser open and raise that instead (Issue #6105)
const auto allWindow = qApp->topLevelWidgets();
auto it = std::find_if(allWindow.cbegin(), allWindow.cend(), [](QWidget *w)
{ return QLatin1String(w->metaObject()->className()) == QLatin1String("OCC::ShibbolethWebView"); });
if (it != allWindow.cend()) {
ownCloudGui::raiseDialog(*it);
return true;
}
}
ownCloudGui::raiseDialog(wiz->_ocWizard); ownCloudGui::raiseDialog(wiz->_ocWizard);
return true; return true;
} }
@@ -140,7 +127,7 @@ void OwncloudSetupWizard::startWizard()
} }
// also checks if an installation is valid and determines auth type in a second step // also checks if an installation is valid and determines auth type in a second step
void OwncloudSetupWizard::slotCheckServer(const QString &urlString) void OwncloudSetupWizard::slotDetermineAuthType(const QString &urlString)
{ {
QString fixedUrl = urlString; QString fixedUrl = urlString;
QUrl url = QUrl::fromUserInput(fixedUrl); QUrl url = QUrl::fromUserInput(fixedUrl);
@@ -163,7 +150,7 @@ void OwncloudSetupWizard::slotCheckServer(const QString &urlString)
// We want to reset the QNAM proxy so that the global proxy settings are used (via ClientProxy settings) // We want to reset the QNAM proxy so that the global proxy settings are used (via ClientProxy settings)
account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy)); account->networkAccessManager()->setProxy(QNetworkProxy(QNetworkProxy::DefaultProxy));
// use a queued invocation so we're as asynchronous as with the other code path // use a queued invocation so we're as asynchronous as with the other code path
QMetaObject::invokeMethod(this, "slotFindServer", Qt::QueuedConnection); QMetaObject::invokeMethod(this, "slotContinueDetermineAuth", Qt::QueuedConnection);
} }
} }
@@ -177,40 +164,20 @@ void OwncloudSetupWizard::slotSystemProxyLookupDone(const QNetworkProxy &proxy)
AccountPtr account = _ocWizard->account(); AccountPtr account = _ocWizard->account();
account->networkAccessManager()->setProxy(proxy); account->networkAccessManager()->setProxy(proxy);
slotFindServer(); slotContinueDetermineAuth();
} }
void OwncloudSetupWizard::slotFindServer() void OwncloudSetupWizard::slotContinueDetermineAuth()
{ {
AccountPtr account = _ocWizard->account(); AccountPtr account = _ocWizard->account();
// Set fake credentials before we check what credential it actually is. // Set fake credentials before we check what credential it actually is.
account->setCredentials(CredentialsFactory::create("dummy")); account->setCredentials(CredentialsFactory::create("dummy"));
// Determining the actual server URL can be a multi-stage process // Before we check the auth type, resolve any permanent redirect
// 1. Check url/status.php with CheckServerJob // chain there might be. We cannot do this only on url/status.php
// If that works we're done. In that case we don't check the // in CheckServerJob, because things like url shorteners don't
// url directly for redirects, see #5954. // redirect subpaths.
// 2. Check the url for permanent redirects (like url shorteners)
// 3. Check redirected-url/status.php with CheckServerJob
// Step 1: Check url/status.php
CheckServerJob *job = new CheckServerJob(account, this);
job->setIgnoreCredentialFailure(true);
connect(job, &CheckServerJob::instanceFound, this, &OwncloudSetupWizard::slotFoundServer);
connect(job, &CheckServerJob::instanceNotFound, this, &OwncloudSetupWizard::slotFindServerBehindRedirect);
connect(job, &CheckServerJob::timeout, this, &OwncloudSetupWizard::slotNoServerFoundTimeout);
job->setTimeout((account->url().scheme() == "https") ? 30 * 1000 : 10 * 1000);
job->start();
// Step 2 and 3 are in slotFindServerBehindRedirect()
}
void OwncloudSetupWizard::slotFindServerBehindRedirect()
{
AccountPtr account = _ocWizard->account();
// Step 2: Resolve any permanent redirect chains on the base url
auto redirectCheckJob = account->sendRequest("GET", account->url()); auto redirectCheckJob = account->sendRequest("GET", account->url());
// Use a significantly reduced timeout for this redirect check: // Use a significantly reduced timeout for this redirect check:
@@ -230,20 +197,20 @@ void OwncloudSetupWizard::slotFindServerBehindRedirect()
} }
}); });
// Step 3: When done, start checking status.php. // When done, start checking status.php.
connect(redirectCheckJob, &SimpleNetworkJob::finishedSignal, this, connect(redirectCheckJob, &SimpleNetworkJob::finishedSignal, this,
[this, account]() { [this, account]() {
CheckServerJob *job = new CheckServerJob(account, this); CheckServerJob *job = new CheckServerJob(account, this);
job->setIgnoreCredentialFailure(true); job->setIgnoreCredentialFailure(true);
connect(job, &CheckServerJob::instanceFound, this, &OwncloudSetupWizard::slotFoundServer); connect(job, &CheckServerJob::instanceFound, this, &OwncloudSetupWizard::slotOwnCloudFoundAuth);
connect(job, &CheckServerJob::instanceNotFound, this, &OwncloudSetupWizard::slotNoServerFound); connect(job, &CheckServerJob::instanceNotFound, this, &OwncloudSetupWizard::slotNoOwnCloudFoundAuth);
connect(job, &CheckServerJob::timeout, this, &OwncloudSetupWizard::slotNoServerFoundTimeout); connect(job, &CheckServerJob::timeout, this, &OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout);
job->setTimeout((account->url().scheme() == "https") ? 30 * 1000 : 10 * 1000); job->setTimeout((account->url().scheme() == "https") ? 30 * 1000 : 10 * 1000);
job->start(); job->start();
}); });
} }
void OwncloudSetupWizard::slotFoundServer(const QUrl &url, const QJsonObject &info) void OwncloudSetupWizard::slotOwnCloudFoundAuth(const QUrl &url, const QJsonObject &info)
{ {
auto serverVersion = CheckServerJob::version(info); auto serverVersion = CheckServerJob::version(info);
@@ -263,10 +230,14 @@ void OwncloudSetupWizard::slotFoundServer(const QUrl &url, const QJsonObject &in
qCInfo(lcWizard) << " was redirected to" << url.toString(); qCInfo(lcWizard) << " was redirected to" << url.toString();
} }
slotDetermineAuthType(); DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_ocWizard->account(), this);
job->setIgnoreCredentialFailure(true);
connect(job, &DetermineAuthTypeJob::authType,
_ocWizard, &OwncloudWizard::setAuthType);
job->start();
} }
void OwncloudSetupWizard::slotNoServerFound(QNetworkReply *reply) void OwncloudSetupWizard::slotNoOwnCloudFoundAuth(QNetworkReply *reply)
{ {
auto job = qobject_cast<CheckServerJob *>(sender()); auto job = qobject_cast<CheckServerJob *>(sender());
int resultCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); int resultCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
@@ -279,7 +250,7 @@ void OwncloudSetupWizard::slotNoServerFound(QNetworkReply *reply)
} else { } else {
msg = tr("Failed to connect to %1 at %2:<br/>%3") msg = tr("Failed to connect to %1 at %2:<br/>%3")
.arg(Utility::escape(Theme::instance()->appNameGUI()), .arg(Utility::escape(Theme::instance()->appNameGUI()),
Utility::escape(_ocWizard->account()->url().toString()), Utility::escape(reply->url().toString()),
Utility::escape(job->errorString())); Utility::escape(job->errorString()));
} }
bool isDowngradeAdvised = checkDowngradeAdvised(reply); bool isDowngradeAdvised = checkDowngradeAdvised(reply);
@@ -294,8 +265,7 @@ void OwncloudSetupWizard::slotNoServerFound(QNetworkReply *reply)
QString serverError = reply->peek(1024 * 20); QString serverError = reply->peek(1024 * 20);
qCDebug(lcWizard) << serverError; qCDebug(lcWizard) << serverError;
QMessageBox messageBox(_ocWizard); QMessageBox messageBox(_ocWizard);
messageBox.setText(tr("The server reported the following error:")); messageBox.setText(serverError);
messageBox.setInformativeText(serverError);
messageBox.addButton(QMessageBox::Ok); messageBox.addButton(QMessageBox::Ok);
messageBox.setTextFormat(Qt::RichText); messageBox.setTextFormat(Qt::RichText);
messageBox.exec(); messageBox.exec();
@@ -309,20 +279,12 @@ void OwncloudSetupWizard::slotNoServerFound(QNetworkReply *reply)
_ocWizard->account()->resetRejectedCertificates(); _ocWizard->account()->resetRejectedCertificates();
} }
void OwncloudSetupWizard::slotNoServerFoundTimeout(const QUrl &url) void OwncloudSetupWizard::slotNoOwnCloudFoundAuthTimeout(const QUrl &url)
{ {
_ocWizard->displayError( _ocWizard->displayError(
tr("Timeout while trying to connect to %1 at %2.") tr("Timeout while trying to connect to %1 at %2.")
.arg(Utility::escape(Theme::instance()->appNameGUI()), Utility::escape(url.toString())), .arg(Utility::escape(Theme::instance()->appNameGUI()), Utility::escape(url.toString())),
false); false);
}
void OwncloudSetupWizard::slotDetermineAuthType()
{
DetermineAuthTypeJob *job = new DetermineAuthTypeJob(_ocWizard->account(), this);
connect(job, &DetermineAuthTypeJob::authType,
_ocWizard, &OwncloudWizard::setAuthType);
job->start();
} }
void OwncloudSetupWizard::slotConnectToOCUrl(const QString &url) void OwncloudSetupWizard::slotConnectToOCUrl(const QString &url)

View File

@@ -49,16 +49,12 @@ signals:
void ownCloudWizardDone(int); void ownCloudWizardDone(int);
private slots: private slots:
void slotCheckServer(const QString &); void slotDetermineAuthType(const QString &);
void slotSystemProxyLookupDone(const QNetworkProxy &proxy); void slotSystemProxyLookupDone(const QNetworkProxy &proxy);
void slotContinueDetermineAuth();
void slotFindServer(); void slotOwnCloudFoundAuth(const QUrl &, const QJsonObject &);
void slotFindServerBehindRedirect(); void slotNoOwnCloudFoundAuth(QNetworkReply *reply);
void slotFoundServer(const QUrl &, const QJsonObject &); void slotNoOwnCloudFoundAuthTimeout(const QUrl &url);
void slotNoServerFound(QNetworkReply *reply);
void slotNoServerFoundTimeout(const QUrl &url);
void slotDetermineAuthType();
void slotConnectToOCUrl(const QString &); void slotConnectToOCUrl(const QString &);
void slotAuthError(); void slotAuthError();

View File

@@ -32,19 +32,6 @@
namespace OCC { namespace OCC {
bool SortedTreeWidgetItem::operator<(const QTreeWidgetItem &other) const
{
int column = treeWidget()->sortColumn();
if (column != 0) {
return QTreeWidgetItem::operator<(other);
}
// Items with empty "File" column are larger than others,
// otherwise sort by time (this uses lexicographic ordering)
return std::forward_as_tuple(text(1).isEmpty(), data(0, Qt::UserRole).toDateTime())
< std::forward_as_tuple(other.text(1).isEmpty(), other.data(0, Qt::UserRole).toDateTime());
}
ProtocolWidget::ProtocolWidget(QWidget *parent) ProtocolWidget::ProtocolWidget(QWidget *parent)
: QWidget(parent) : QWidget(parent)
, _ui(new Ui::ProtocolWidget) , _ui(new Ui::ProtocolWidget)
@@ -99,16 +86,6 @@ void ProtocolWidget::showEvent(QShowEvent *ev)
{ {
ConfigFile cfg; ConfigFile cfg;
cfg.restoreGeometryHeader(_ui->_treeWidget->header()); cfg.restoreGeometryHeader(_ui->_treeWidget->header());
// Sorting by section was newly enabled. But if we restore the header
// from a state where sorting was disabled, both of these flags will be
// false and sorting will be impossible!
_ui->_treeWidget->header()->setSectionsClickable(true);
_ui->_treeWidget->header()->setSortIndicatorShown(true);
// Switch back to "by time" ordering
_ui->_treeWidget->sortByColumn(0, Qt::DescendingOrder);
QWidget::showEvent(ev); QWidget::showEvent(ev);
} }
@@ -181,15 +158,14 @@ QTreeWidgetItem *ProtocolWidget::createCompletedTreewidgetItem(const QString &fo
columns << Utility::octetsToString(item._size); columns << Utility::octetsToString(item._size);
} }
QTreeWidgetItem *twitem = new SortedTreeWidgetItem(columns); QTreeWidgetItem *twitem = new QTreeWidgetItem(columns);
twitem->setData(0, Qt::SizeHintRole, QSize(0, ActivityItemDelegate::rowHeight())); twitem->setData(0, Qt::SizeHintRole, QSize(0, ActivityItemDelegate::rowHeight()));
twitem->setData(0, Qt::UserRole, timestamp);
twitem->setIcon(0, icon); twitem->setIcon(0, icon);
twitem->setToolTip(0, longTimeStr); twitem->setToolTip(0, longTimeStr);
twitem->setToolTip(1, item._file); twitem->setToolTip(1, item._file);
twitem->setData(2, Qt::UserRole, folder);
twitem->setToolTip(3, message); twitem->setToolTip(3, message);
twitem->setData(3, Qt::UserRole, item._status); twitem->setData(0, Qt::UserRole, item._status);
twitem->setData(2, Qt::UserRole, folder);
return twitem; return twitem;
} }

View File

@@ -34,21 +34,6 @@ namespace Ui {
} }
class Application; class Application;
/**
* A QTreeWidgetItem with special sorting.
*
* It allows items for global entries to be moved to the top if the
* sorting section is the "Time" column.
*/
class SortedTreeWidgetItem : public QTreeWidgetItem
{
public:
using QTreeWidgetItem::QTreeWidgetItem;
private:
bool operator<(const QTreeWidgetItem &other) const override;
};
/** /**
* @brief The ProtocolWidget class * @brief The ProtocolWidget class
* @ingroup gui * @ingroup gui

View File

@@ -35,9 +35,6 @@
<property name="uniformRowHeights"> <property name="uniformRowHeights">
<bool>true</bool> <bool>true</bool>
</property> </property>
<property name="sortingEnabled">
<bool>true</bool>
</property>
<property name="columnCount"> <property name="columnCount">
<number>4</number> <number>4</number>
</property> </property>

View File

@@ -55,8 +55,6 @@ static const float buttonSizeRatio = 1.618; // golden ratio
namespace OCC { namespace OCC {
#include "settingsdialogcommon.cpp"
static QIcon circleMask(const QImage &avatar) static QIcon circleMask(const QImage &avatar)
{ {
int dim = avatar.width(); int dim = avatar.width();
@@ -238,7 +236,7 @@ void SettingsDialog::accountAdded(AccountState *s)
if (!brandingSingleAccount) { if (!brandingSingleAccount) {
accountAction->setToolTip(s->account()->displayName()); accountAction->setToolTip(s->account()->displayName());
accountAction->setIconText(SettingsDialogCommon::shortDisplayNameForSettings(s->account().data(), height * buttonSizeRatio)); accountAction->setIconText(s->shortDisplayNameForSettings(height * buttonSizeRatio));
} }
_toolBar->insertAction(_toolBar->actions().at(0), accountAction); _toolBar->insertAction(_toolBar->actions().at(0), accountAction);
auto accountSettings = new AccountSettings(s, this); auto accountSettings = new AccountSettings(s, this);
@@ -252,7 +250,6 @@ void SettingsDialog::accountAdded(AccountState *s)
_gui, &ownCloudGui::slotFolderOpenAction); _gui, &ownCloudGui::slotFolderOpenAction);
connect(accountSettings, &AccountSettings::showIssuesList, this, &SettingsDialog::showIssuesList); connect(accountSettings, &AccountSettings::showIssuesList, this, &SettingsDialog::showIssuesList);
connect(s->account().data(), &Account::accountChangedAvatar, this, &SettingsDialog::slotAccountAvatarChanged); connect(s->account().data(), &Account::accountChangedAvatar, this, &SettingsDialog::slotAccountAvatarChanged);
connect(s->account().data(), &Account::accountChangedDisplayName, this, &SettingsDialog::slotAccountDisplayNameChanged);
slotRefreshActivity(s); slotRefreshActivity(s);
} }
@@ -271,20 +268,6 @@ void SettingsDialog::slotAccountAvatarChanged()
} }
} }
void SettingsDialog::slotAccountDisplayNameChanged()
{
Account *account = static_cast<Account *>(sender());
if (account && _actionForAccount.contains(account)) {
QAction *action = _actionForAccount[account];
if (action) {
QString displayName = account->displayName();
action->setText(displayName);
auto height = _toolBar->sizeHint().height();
action->setIconText(SettingsDialogCommon::shortDisplayNameForSettings(account, height * buttonSizeRatio));
}
}
}
void SettingsDialog::accountRemoved(AccountState *s) void SettingsDialog::accountRemoved(AccountState *s)
{ {
for (auto it = _actionGroupWidgets.begin(); it != _actionGroupWidgets.end(); ++it) { for (auto it = _actionGroupWidgets.begin(); it != _actionGroupWidgets.end(); ++it) {

View File

@@ -60,7 +60,6 @@ public slots:
void slotSwitchPage(QAction *action); void slotSwitchPage(QAction *action);
void slotRefreshActivity(AccountState *accountState); void slotRefreshActivity(AccountState *accountState);
void slotAccountAvatarChanged(); void slotAccountAvatarChanged();
void slotAccountDisplayNameChanged();
protected: protected:
void reject() Q_DECL_OVERRIDE; void reject() Q_DECL_OVERRIDE;

View File

@@ -1,28 +0,0 @@
namespace SettingsDialogCommon
{
/** display name with two lines that is displayed in the settings
* If width is bigger than 0, the string will be ellided so it does not exceed that width
*/
QString shortDisplayNameForSettings(Account* account, int width)
{
QString user = account->davDisplayName();
if (user.isEmpty()) {
user = account->credentials()->user();
}
QString host = account->url().host();
int port = account->url().port();
if (port > 0 && port != 80 && port != 443) {
host.append(QLatin1Char(':'));
host.append(QString::number(port));
}
if (width > 0) {
QFont f;
QFontMetrics fm(f);
host = fm.elidedText(host, Qt::ElideMiddle, width);
user = fm.elidedText(user, Qt::ElideRight, width);
}
return user + QLatin1String("\n") + host;
}
}

View File

@@ -38,9 +38,6 @@
namespace OCC { namespace OCC {
#include "settingsdialogcommon.cpp"
// Duplicate in settingsdialog.cpp // Duplicate in settingsdialog.cpp
static QIcon circleMask(const QImage &avatar) static QIcon circleMask(const QImage &avatar)
{ {
@@ -149,7 +146,7 @@ void SettingsDialogMac::accountAdded(AccountState *s)
QIcon accountIcon = MacStandardIcon::icon(MacStandardIcon::UserAccounts); QIcon accountIcon = MacStandardIcon::icon(MacStandardIcon::UserAccounts);
auto accountSettings = new AccountSettings(s, this); auto accountSettings = new AccountSettings(s, this);
QString displayName = Theme::instance()->multiAccount() ? SettingsDialogCommon::shortDisplayNameForSettings(s->account().data(), 0) : tr("Account"); QString displayName = Theme::instance()->multiAccount() ? s->shortDisplayNameForSettings() : tr("Account");
insertPreferencesPanel(0, accountIcon, displayName, accountSettings); insertPreferencesPanel(0, accountIcon, displayName, accountSettings);
@@ -157,8 +154,7 @@ void SettingsDialogMac::accountAdded(AccountState *s)
connect(accountSettings, &AccountSettings::openFolderAlias, _gui, &ownCloudGui::slotFolderOpenAction); connect(accountSettings, &AccountSettings::openFolderAlias, _gui, &ownCloudGui::slotFolderOpenAction);
connect(accountSettings, &AccountSettings::showIssuesList, this, &SettingsDialogMac::showIssuesList); connect(accountSettings, &AccountSettings::showIssuesList, this, &SettingsDialogMac::showIssuesList);
connect(s->account().data(), &Account::accountChangedAvatar, this, &SettingsDialogMac::slotAccountAvatarChanged); connect(s->account().data(), SIGNAL(accountChangedAvatar()), this, SLOT(slotAccountAvatarChanged()));
connect(s->account().data(), &Account::accountChangedDisplayName, this, &SettingsDialogMac::slotAccountDisplayNameChanged);
slotRefreshActivity(s); slotRefreshActivity(s);
} }
@@ -196,23 +192,4 @@ void SettingsDialogMac::slotAccountAvatarChanged()
} }
} }
} }
void SettingsDialogMac::slotAccountDisplayNameChanged()
{
Account *account = static_cast<Account *>(sender());
auto list = findChildren<AccountSettings *>(QString());
foreach (auto p, list) {
if (p->accountsState()->account() == account) {
int idx = indexForPanel(p);
QString displayName = account->displayName();
if (!displayName.isNull()) {
displayName = Theme::instance()->multiAccount()
? SettingsDialogCommon::shortDisplayNameForSettings(account, 0)
: tr("Account");
setPreferencesPanelTitle(idx, displayName);
}
}
}
}
} }

View File

@@ -54,7 +54,6 @@ private slots:
void accountAdded(AccountState *); void accountAdded(AccountState *);
void accountRemoved(AccountState *); void accountRemoved(AccountState *);
void slotAccountAvatarChanged(); void slotAccountAvatarChanged();
void slotAccountDisplayNameChanged();
private: private:
void closeEvent(QCloseEvent *event); void closeEvent(QCloseEvent *event);

View File

@@ -133,7 +133,6 @@ ShareDialog::ShareDialog(QPointer<AccountState> accountState,
job->setProperties( job->setProperties(
QList<QByteArray>() QList<QByteArray>()
<< "http://open-collaboration-services.org/ns:share-permissions" << "http://open-collaboration-services.org/ns:share-permissions"
<< "http://owncloud.org/ns:fileid" // numeric file id for fallback private link generation
<< "http://owncloud.org/ns:privatelink"); << "http://owncloud.org/ns:privatelink");
job->setTimeout(10 * 1000); job->setTimeout(10 * 1000);
connect(job, &PropfindJob::result, this, &ShareDialog::slotPropfindReceived); connect(job, &PropfindJob::result, this, &ShareDialog::slotPropfindReceived);
@@ -161,13 +160,9 @@ void ShareDialog::slotPropfindReceived(const QVariantMap &result)
qCInfo(lcSharing) << "Received sharing permissions for" << _sharePath << _maxSharingPermissions; qCInfo(lcSharing) << "Received sharing permissions for" << _sharePath << _maxSharingPermissions;
} }
auto privateLinkUrl = result["privatelink"].toString(); auto privateLinkUrl = result["privatelink"].toString();
auto numericFileId = result["fileid"].toByteArray();
if (!privateLinkUrl.isEmpty()) { if (!privateLinkUrl.isEmpty()) {
qCInfo(lcSharing) << "Received private link url for" << _sharePath << privateLinkUrl; qCInfo(lcSharing) << "Received private link url for" << _sharePath << privateLinkUrl;
_privateLinkUrl = privateLinkUrl; _privateLinkUrl = privateLinkUrl;
} else if (!numericFileId.isEmpty()) {
qCInfo(lcSharing) << "Received numeric file id for" << _sharePath << numericFileId;
_privateLinkUrl = _accountState->account()->deprecatedPrivateLinkUrl(numericFileId).toString(QUrl::FullyEncoded);
} }
showSharingUi(); showSharingUi();

View File

@@ -155,15 +155,14 @@ ShareLinkWidget::ShareLinkWidget(AccountPtr account,
// Prepare sharing menu // Prepare sharing menu
_linkContextMenu = new QMenu(this); _shareLinkMenu = new QMenu(this);
connect(_linkContextMenu, &QMenu::triggered, connect(_shareLinkMenu, &QMenu::triggered,
this, &ShareLinkWidget::slotLinkContextMenuActionTriggered); this, &ShareLinkWidget::slotShareLinkActionTriggered);
_openLinkAction = _linkContextMenu->addAction(tr("Open link in browser")); _openLinkAction = _shareLinkMenu->addAction(tr("Open link in browser"));
_copyLinkAction = _linkContextMenu->addAction(tr("Copy link to clipboard")); _copyLinkAction = _shareLinkMenu->addAction(tr("Copy link to clipboard"));
_copyDirectLinkAction = _linkContextMenu->addAction(tr("Copy link to clipboard (direct download)")); _copyDirectLinkAction = _shareLinkMenu->addAction(tr("Copy link to clipboard (direct download)"));
_emailLinkAction = _linkContextMenu->addAction(tr("Send link by email")); _emailLinkAction = _shareLinkMenu->addAction(tr("Send link by email"));
_emailDirectLinkAction = _linkContextMenu->addAction(tr("Send link by email (direct download)")); _emailDirectLinkAction = _shareLinkMenu->addAction(tr("Send link by email (direct download)"));
_deleteLinkAction = _linkContextMenu->addAction(tr("Delete"));
/* /*
* Create the share manager and connect it properly * Create the share manager and connect it properly
@@ -232,24 +231,28 @@ void ShareLinkWidget::slotSharesFetched(const QList<QSharedPointer<Share>> &shar
table->insertRow(row); table->insertRow(row);
auto nameItem = new QTableWidgetItem; auto nameItem = new QTableWidgetItem;
auto name = shareName(*linkShare); QString name = linkShare->getName();
if (!_namesSupported) { if (name.isEmpty()) {
nameItem->setFlags(nameItem->flags() & ~Qt::ItemIsEditable); if (!_namesSupported) {
name = tr("Public link");
nameItem->setFlags(nameItem->flags() & ~Qt::ItemIsEditable);
} else {
name = linkShare->getToken();
}
} }
nameItem->setText(name); nameItem->setText(name);
nameItem->setData(Qt::UserRole, QVariant::fromValue(linkShare)); nameItem->setData(Qt::UserRole, QVariant::fromValue(linkShare));
table->setItem(row, 0, nameItem); table->setItem(row, 0, nameItem);
auto dotdotdotButton = new QToolButton; auto shareButton = new QToolButton;
dotdotdotButton->setText("..."); shareButton->setText("...");
dotdotdotButton->setProperty(propertyShareC, QVariant::fromValue(linkShare)); shareButton->setProperty(propertyShareC, QVariant::fromValue(linkShare));
connect(dotdotdotButton, &QAbstractButton::clicked, this, &ShareLinkWidget::slotContextMenuButtonClicked); connect(shareButton, &QAbstractButton::clicked, this, &ShareLinkWidget::slotShareLinkButtonClicked);
table->setCellWidget(row, 1, dotdotdotButton); table->setCellWidget(row, 1, shareButton);
auto deleteButton = new QToolButton; auto deleteButton = new QToolButton;
deleteButton->setIcon(deleteIcon); deleteButton->setIcon(deleteIcon);
deleteButton->setProperty(propertyShareC, QVariant::fromValue(linkShare)); deleteButton->setProperty(propertyShareC, QVariant::fromValue(linkShare));
deleteButton->setToolTip(tr("Delete link share"));
connect(deleteButton, &QAbstractButton::clicked, this, &ShareLinkWidget::slotDeleteShareClicked); connect(deleteButton, &QAbstractButton::clicked, this, &ShareLinkWidget::slotDeleteShareClicked);
table->setCellWidget(row, 2, deleteButton); table->setCellWidget(row, 2, deleteButton);
@@ -511,56 +514,22 @@ void ShareLinkWidget::openShareLink(const QUrl &url)
Utility::openBrowser(url, this); Utility::openBrowser(url, this);
} }
void ShareLinkWidget::confirmAndDeleteShare(const QSharedPointer<LinkShare> &share) void ShareLinkWidget::slotShareLinkButtonClicked()
{
auto messageBox = new QMessageBox(
QMessageBox::Question,
tr("Confirm Link Share Deletion"),
tr("<p>Do you really want to delete the public link share <i>%1</i>?</p>"
"<p>Note: This action cannot be undone.</p>")
.arg(shareName(*share)),
QMessageBox::NoButton,
this);
QPushButton *yesButton =
messageBox->addButton(tr("Delete"), QMessageBox::YesRole);
messageBox->addButton(tr("Cancel"), QMessageBox::NoRole);
connect(messageBox, &QMessageBox::finished, this,
[messageBox, yesButton, share]() {
if (messageBox->clickedButton() == yesButton)
share->deleteShare();
});
messageBox->open();
}
QString ShareLinkWidget::shareName(const LinkShare &share) const
{
QString name = share.getName();
if (!name.isEmpty())
return name;
if (!_namesSupported)
return tr("Public link");
return share.getToken();
}
void ShareLinkWidget::slotContextMenuButtonClicked()
{ {
auto share = sender()->property(propertyShareC).value<QSharedPointer<LinkShare>>(); auto share = sender()->property(propertyShareC).value<QSharedPointer<LinkShare>>();
bool downloadEnabled = share->getShowFileListing(); bool downloadEnabled = share->getShowFileListing();
_copyDirectLinkAction->setVisible(downloadEnabled); _copyDirectLinkAction->setVisible(downloadEnabled);
_emailDirectLinkAction->setVisible(downloadEnabled); _emailDirectLinkAction->setVisible(downloadEnabled);
_linkContextMenu->setProperty(propertyShareC, QVariant::fromValue(share)); _shareLinkMenu->setProperty(propertyShareC, QVariant::fromValue(share));
_linkContextMenu->exec(QCursor::pos()); _shareLinkMenu->exec(QCursor::pos());
} }
void ShareLinkWidget::slotLinkContextMenuActionTriggered(QAction *action) void ShareLinkWidget::slotShareLinkActionTriggered(QAction *action)
{ {
auto share = sender()->property(propertyShareC).value<QSharedPointer<LinkShare>>(); auto share = sender()->property(propertyShareC).value<QSharedPointer<LinkShare>>();
if (action == _deleteLinkAction) { if (action == _copyLinkAction) {
confirmAndDeleteShare(share);
} else if (action == _copyLinkAction) {
QApplication::clipboard()->setText(share->getLink().toString()); QApplication::clipboard()->setText(share->getLink().toString());
} else if (action == _copyDirectLinkAction) { } else if (action == _copyDirectLinkAction) {
QApplication::clipboard()->setText(share->getDirectDownloadLink().toString()); QApplication::clipboard()->setText(share->getDirectDownloadLink().toString());
@@ -576,7 +545,7 @@ void ShareLinkWidget::slotLinkContextMenuActionTriggered(QAction *action)
void ShareLinkWidget::slotDeleteShareClicked() void ShareLinkWidget::slotDeleteShareClicked()
{ {
auto share = sender()->property(propertyShareC).value<QSharedPointer<LinkShare>>(); auto share = sender()->property(propertyShareC).value<QSharedPointer<LinkShare>>();
confirmAndDeleteShare(share); share->deleteShare();
} }
void ShareLinkWidget::slotPermissionsCheckboxClicked() void ShareLinkWidget::slotPermissionsCheckboxClicked()

View File

@@ -70,8 +70,8 @@ private slots:
void slotPasswordChanged(const QString &newText); void slotPasswordChanged(const QString &newText);
void slotNameEdited(QTableWidgetItem *item); void slotNameEdited(QTableWidgetItem *item);
void slotContextMenuButtonClicked(); void slotShareLinkButtonClicked();
void slotLinkContextMenuActionTriggered(QAction *action); void slotShareLinkActionTriggered(QAction *action);
void slotDeleteShareFetched(); void slotDeleteShareFetched();
void slotCreateShareFetched(const QSharedPointer<LinkShare> &share); void slotCreateShareFetched(const QSharedPointer<LinkShare> &share);
@@ -93,12 +93,6 @@ private:
void emailShareLink(const QUrl &url); void emailShareLink(const QUrl &url);
void openShareLink(const QUrl &url); void openShareLink(const QUrl &url);
/** Confirm with the user and then delete the share */
void confirmAndDeleteShare(const QSharedPointer<LinkShare> &share);
/** Retrieve a share's name, accounting for _namesSupported */
QString shareName(const LinkShare &share) const;
/** /**
* Retrieve the selected share, returning 0 if none. * Retrieve the selected share, returning 0 if none.
*/ */
@@ -126,13 +120,12 @@ private:
// the next time getShares() finishes. This stores its id. // the next time getShares() finishes. This stores its id.
QString _newShareOverrideSelectionId; QString _newShareOverrideSelectionId;
QMenu *_linkContextMenu = nullptr; QMenu *_shareLinkMenu;
QAction *_deleteLinkAction = nullptr; QAction *_openLinkAction;
QAction *_openLinkAction = nullptr; QAction *_copyLinkAction;
QAction *_copyLinkAction = nullptr; QAction *_copyDirectLinkAction;
QAction *_copyDirectLinkAction = nullptr; QAction *_emailLinkAction;
QAction *_emailLinkAction = nullptr; QAction *_emailDirectLinkAction;
QAction *_emailDirectLinkAction = nullptr;
}; };
} }

View File

@@ -15,40 +15,24 @@
#include "sharemanager.h" #include "sharemanager.h"
#include "ocssharejob.h" #include "ocssharejob.h"
#include "account.h" #include "account.h"
#include "folderman.h"
#include "accountstate.h"
#include <QUrl> #include <QUrl>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
#include <QJsonArray> #include <QJsonArray>
namespace OCC { namespace {
struct CreateShare
/**
* When a share is modified, we need to tell the folders so they can adjust overlay icons
*/
static void updateFolder(const AccountPtr &account, const QString &path)
{ {
foreach (Folder *f, FolderMan::instance()->map()) { QString path;
if (f->accountState()->account() != account) OCC::Share::ShareType shareType;
continue; QString shareWith;
auto folderPath = f->remotePath(); OCC::Share::Permissions permissions;
if (path.startsWith(folderPath) && (path == folderPath || folderPath.endsWith('/') || path[folderPath.size()] == '/')) { };
// Workaround the fact that the server does not invalidate the etags of parent directories } // anonymous namespace
// when something is shared. Q_DECLARE_METATYPE(CreateShare)
auto relative = path.midRef(folderPath.size());
if (relative.startsWith('/'))
relative = relative.mid(1);
f->journalDb()->avoidReadFromDbOnNextSync(relative.toString());
// Schedule a sync so it can update the remote permission flag and let the socket API
// know about the shared icon.
f->scheduleThisFolderSoon();
}
}
}
namespace OCC {
Share::Share(AccountPtr account, Share::Share(AccountPtr account,
const QString &id, const QString &id,
@@ -70,11 +54,6 @@ AccountPtr Share::account() const
return _account; return _account;
} }
QString Share::path() const
{
return _path;
}
QString Share::getId() const QString Share::getId() const
{ {
return _id; return _id;
@@ -120,8 +99,6 @@ void Share::deleteShare()
void Share::slotDeleted() void Share::slotDeleted()
{ {
emit shareDeleted(); emit shareDeleted();
updateFolder(_account, _path);
} }
void Share::slotOcsError(int statusCode, const QString &message) void Share::slotOcsError(int statusCode, const QString &message)
@@ -281,8 +258,6 @@ void ShareManager::slotLinkShareCreated(const QJsonDocument &reply)
QSharedPointer<LinkShare> share(parseLinkShare(data)); QSharedPointer<LinkShare> share(parseLinkShare(data));
emit linkShareCreated(share); emit linkShareCreated(share);
updateFolder(_account, share->path());
} }
@@ -292,34 +267,51 @@ void ShareManager::createShare(const QString &path,
const Share::Permissions permissions) const Share::Permissions permissions)
{ {
auto job = new OcsShareJob(_account); auto job = new OcsShareJob(_account);
// Store values that we need for creating this share later.
CreateShare continuation;
continuation.path = path;
continuation.shareType = shareType;
continuation.shareWith = shareWith;
continuation.permissions = permissions;
_jobContinuation[job] = QVariant::fromValue(continuation);
connect(job, &OcsShareJob::shareJobFinished, this, &ShareManager::slotCreateShare);
connect(job, &OcsJob::ocsError, this, &ShareManager::slotOcsError); connect(job, &OcsJob::ocsError, this, &ShareManager::slotOcsError);
connect(job, &OcsShareJob::shareJobFinished, this,
[=](const QJsonDocument &reply) {
// Find existing share permissions (if this was shared with us)
Share::Permissions existingPermissions = SharePermissionDefault;
foreach (const QJsonValue &element, reply.object()["ocs"].toObject()["data"].toArray()) {
auto map = element.toObject();
if (map["file_target"] == path)
existingPermissions = Share::Permissions(map["permissions"].toInt());
}
// Limit the permissions we request for a share to the ones the item
// was shared with initially.
auto perm = permissions;
if (permissions == SharePermissionDefault) {
perm = existingPermissions;
} else if (existingPermissions != SharePermissionDefault) {
perm &= existingPermissions;
}
OcsShareJob *job = new OcsShareJob(_account);
connect(job, &OcsShareJob::shareJobFinished, this, &ShareManager::slotShareCreated);
connect(job, &OcsJob::ocsError, this, &ShareManager::slotOcsError);
job->createShare(path, shareType, shareWith, permissions);
});
job->getSharedWithMe(); job->getSharedWithMe();
} }
void ShareManager::slotCreateShare(const QJsonDocument &reply)
{
if (!_jobContinuation.contains(sender()))
return;
CreateShare cont = _jobContinuation[sender()].value<CreateShare>();
if (cont.path.isEmpty())
return;
_jobContinuation.remove(sender());
// Find existing share permissions (if this was shared with us)
Share::Permissions existingPermissions = SharePermissionDefault;
foreach (const QJsonValue &element, reply.object()["ocs"].toObject()["data"].toArray()) {
auto map = element.toObject();
if (map["file_target"] == cont.path)
existingPermissions = Share::Permissions(map["permissions"].toInt());
}
// Limit the permissions we request for a share to the ones the item
// was shared with initially.
if (cont.permissions == SharePermissionDefault) {
cont.permissions = existingPermissions;
} else if (existingPermissions != SharePermissionDefault) {
cont.permissions &= existingPermissions;
}
OcsShareJob *job = new OcsShareJob(_account);
connect(job, &OcsShareJob::shareJobFinished, this, &ShareManager::slotShareCreated);
connect(job, &OcsJob::ocsError, this, &ShareManager::slotOcsError);
job->createShare(cont.path, cont.shareType, cont.shareWith, cont.permissions);
}
void ShareManager::slotShareCreated(const QJsonDocument &reply) void ShareManager::slotShareCreated(const QJsonDocument &reply)
{ {
@@ -328,8 +320,6 @@ void ShareManager::slotShareCreated(const QJsonDocument &reply)
QSharedPointer<Share> share(parseShare(data)); QSharedPointer<Share> share(parseShare(data));
emit shareCreated(share); emit shareCreated(share);
updateFolder(_account, share->path());
} }
void ShareManager::fetchShares(const QString &path) void ShareManager::fetchShares(const QString &path)

View File

@@ -64,8 +64,6 @@ public:
*/ */
AccountPtr account() const; AccountPtr account() const;
QString path() const;
/* /*
* Get the id * Get the id
*/ */
@@ -295,10 +293,13 @@ private slots:
void slotLinkShareCreated(const QJsonDocument &reply); void slotLinkShareCreated(const QJsonDocument &reply);
void slotShareCreated(const QJsonDocument &reply); void slotShareCreated(const QJsonDocument &reply);
void slotOcsError(int statusCode, const QString &message); void slotOcsError(int statusCode, const QString &message);
void slotCreateShare(const QJsonDocument &reply);
private: private:
QSharedPointer<LinkShare> parseLinkShare(const QJsonObject &data); QSharedPointer<LinkShare> parseLinkShare(const QJsonObject &data);
QSharedPointer<Share> parseShare(const QJsonObject &data); QSharedPointer<Share> parseShare(const QJsonObject &data);
QMap<QObject *, QVariant> _jobContinuation;
AccountPtr _account; AccountPtr _account;
}; };
} }

View File

@@ -503,29 +503,27 @@ void fetchPrivateLinkUrl(const QString &localFile, SocketApi *target, void (Sock
const QString localFileClean = QDir::cleanPath(localFile); const QString localFileClean = QDir::cleanPath(localFile);
const QString file = localFileClean.mid(shareFolder->cleanPath().length() + 1); const QString file = localFileClean.mid(shareFolder->cleanPath().length() + 1);
AccountPtr account = shareFolder->accountState()->account();
// Generate private link ourselves: used as a fallback // Generate private link ourselves: used as a fallback
SyncJournalFileRecord rec; SyncJournalFileRecord rec;
if (!shareFolder->journalDb()->getFileRecord(file, &rec) || !rec.isValid()) if (!shareFolder->journalDb()->getFileRecord(file, &rec) || !rec.isValid())
return; return;
const QString oldUrl = const QString oldUrl =
account->deprecatedPrivateLinkUrl(rec.numericFileId()).toString(QUrl::FullyEncoded); shareFolder->accountState()->account()->deprecatedPrivateLinkUrl(rec.numericFileId()).toString(QUrl::FullyEncoded);
// Retrieve the new link or numeric file id by PROPFIND // If the server doesn't have the property, use the old url directly.
PropfindJob *job = new PropfindJob(account, file, target); if (!shareFolder->accountState()->account()->capabilities().privateLinkPropertyAvailable()) {
job->setProperties( (target->*targetFun)(oldUrl);
QList<QByteArray>() return;
<< "http://owncloud.org/ns:fileid" // numeric file id for fallback private link generation }
<< "http://owncloud.org/ns:privatelink");
// Retrieve the new link by PROPFIND
PropfindJob *job = new PropfindJob(shareFolder->accountState()->account(), file, target);
job->setProperties(QList<QByteArray>() << "http://owncloud.org/ns:privatelink");
job->setTimeout(10 * 1000); job->setTimeout(10 * 1000);
QObject::connect(job, &PropfindJob::result, target, [=](const QVariantMap &result) { QObject::connect(job, &PropfindJob::result, target, [=](const QVariantMap &result) {
auto privateLinkUrl = result["privatelink"].toString(); auto privateLinkUrl = result["privatelink"].toString();
auto numericFileId = result["fileid"].toByteArray();
if (!privateLinkUrl.isEmpty()) { if (!privateLinkUrl.isEmpty()) {
(target->*targetFun)(privateLinkUrl); (target->*targetFun)(privateLinkUrl);
} else if (!numericFileId.isEmpty()) {
(target->*targetFun)(account->deprecatedPrivateLinkUrl(numericFileId).toString(QUrl::FullyEncoded));
} else { } else {
(target->*targetFun)(oldUrl); (target->*targetFun)(oldUrl);
} }

View File

@@ -201,15 +201,13 @@ bool OwncloudSetupPage::urlHasChanged()
int OwncloudSetupPage::nextId() const int OwncloudSetupPage::nextId() const
{ {
switch (_authType) { if (_authType == DetermineAuthTypeJob::Basic) {
case DetermineAuthTypeJob::Basic:
return WizardCommon::Page_HttpCreds; return WizardCommon::Page_HttpCreds;
case DetermineAuthTypeJob::OAuth: } else if (_authType == DetermineAuthTypeJob::OAuth) {
return WizardCommon::Page_OAuthCreds; return WizardCommon::Page_OAuthCreds;
case DetermineAuthTypeJob::Shibboleth: } else {
return WizardCommon::Page_ShibbolethCreds; return WizardCommon::Page_ShibbolethCreds;
} }
return WizardCommon::Page_HttpCreds;
} }
QString OwncloudSetupPage::url() const QString OwncloudSetupPage::url() const

View File

@@ -135,7 +135,6 @@ void AbstractNetworkJob::adoptRequest(QNetworkReply *reply)
addTimer(reply); addTimer(reply);
setReply(reply); setReply(reply);
setupConnections(reply); setupConnections(reply);
newReplyHook(reply);
} }
QUrl AbstractNetworkJob::makeAccountUrl(const QString &relativePath) const QUrl AbstractNetworkJob::makeAccountUrl(const QString &relativePath) const
@@ -173,6 +172,8 @@ void AbstractNetworkJob::slotFinished()
QUrl requestedUrl = reply()->request().url(); QUrl requestedUrl = reply()->request().url();
QUrl redirectUrl = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); QUrl redirectUrl = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
if (_followRedirects && !redirectUrl.isEmpty()) { if (_followRedirects && !redirectUrl.isEmpty()) {
_redirectCount++;
// Redirects may be relative // Redirects may be relative
if (redirectUrl.isRelative()) if (redirectUrl.isRelative())
redirectUrl = requestedUrl.resolved(redirectUrl); redirectUrl = requestedUrl.resolved(redirectUrl);
@@ -193,32 +194,27 @@ void AbstractNetworkJob::slotFinished()
QByteArray verb = requestVerb(*reply()); QByteArray verb = requestVerb(*reply());
if (requestedUrl.scheme() == QLatin1String("https") && redirectUrl.scheme() == QLatin1String("http")) { if (requestedUrl.scheme() == QLatin1String("https") && redirectUrl.scheme() == QLatin1String("http")) {
qCWarning(lcNetworkJob) << this << "HTTPS->HTTP downgrade detected!"; qCWarning(lcNetworkJob) << this << "HTTPS->HTTP downgrade detected!";
} else if (requestedUrl == redirectUrl || _redirectCount + 1 >= maxRedirects()) { } else if (requestedUrl == redirectUrl || _redirectCount >= maxRedirects()) {
qCWarning(lcNetworkJob) << this << "Redirect loop detected!"; qCWarning(lcNetworkJob) << this << "Redirect loop detected!";
} else if (_requestBody && _requestBody->isSequential()) { } else if (_requestBody && _requestBody->isSequential()) {
qCWarning(lcNetworkJob) << this << "cannot redirect request with sequential body"; qCWarning(lcNetworkJob) << this << "cannot redirect request with sequential body";
} else if (verb.isEmpty()) { } else if (verb.isEmpty()) {
qCWarning(lcNetworkJob) << this << "cannot redirect request: could not detect original verb"; qCWarning(lcNetworkJob) << this << "cannot redirect request: could not detect original verb";
} else { } else {
emit redirected(_reply, redirectUrl, _redirectCount); emit redirected(_reply, redirectUrl, _redirectCount - 1);
// The signal emission may have changed this value // Create the redirected request and send it
if (_followRedirects) { qCInfo(lcNetworkJob) << "Redirecting" << verb << requestedUrl << redirectUrl;
_redirectCount++; resetTimeout();
if (_requestBody) {
// Create the redirected request and send it _requestBody->seek(0);
qCInfo(lcNetworkJob) << "Redirecting" << verb << requestedUrl << redirectUrl;
resetTimeout();
if (_requestBody) {
_requestBody->seek(0);
}
sendRequest(
verb,
redirectUrl,
reply()->request(),
_requestBody);
return;
} }
sendRequest(
verb,
redirectUrl,
reply()->request(),
_requestBody);
return;
} }
} }

View File

@@ -66,7 +66,6 @@ public:
* requests where custom handling is necessary. * requests where custom handling is necessary.
*/ */
void setFollowRedirects(bool follow); void setFollowRedirects(bool follow);
bool followRedirects() const { return _followRedirects; }
QByteArray responseTimestamp(); QByteArray responseTimestamp();
@@ -108,6 +107,8 @@ signals:
void redirected(QNetworkReply *reply, const QUrl &targetUrl, int redirectCount); void redirected(QNetworkReply *reply, const QUrl &targetUrl, int redirectCount);
protected: protected:
void setupConnections(QNetworkReply *reply);
/** Initiate a network request, returning a QNetworkReply. /** Initiate a network request, returning a QNetworkReply.
* *
* Calls setReply() and setupConnections() on it. * Calls setReply() and setupConnections() on it.
@@ -132,16 +133,6 @@ protected:
*/ */
void adoptRequest(QNetworkReply *reply); void adoptRequest(QNetworkReply *reply);
void setupConnections(QNetworkReply *reply);
/** Can be used by derived classes to set up the network reply.
*
* Particularly useful when the request is redirected and reply()
* changes. For things like setting up additional signal connections
* on the new reply.
*/
virtual void newReplyHook(QNetworkReply *) {}
/// Creates a url for the account from a relative path /// Creates a url for the account from a relative path
QUrl makeAccountUrl(const QString &relativePath) const; QUrl makeAccountUrl(const QString &relativePath) const;

View File

@@ -93,7 +93,6 @@ void Account::setDavUser(const QString &newDavUser)
_davUser = newDavUser; _davUser = newDavUser;
} }
#ifndef TOKEN_AUTH_ONLY
QImage Account::avatar() const QImage Account::avatar() const
{ {
return _avatarImg; return _avatarImg;
@@ -103,11 +102,10 @@ void Account::setAvatar(const QImage &img)
_avatarImg = img; _avatarImg = img;
emit accountChangedAvatar(); emit accountChangedAvatar();
} }
#endif
QString Account::displayName() const QString Account::displayName() const
{ {
QString dn = QString("%1@%2").arg(davUser(), _url.host()); QString dn = QString("%1@%2").arg(_credentials->user(), _url.host());
int port = url().port(); int port = url().port();
if (port > 0 && port != 80 && port != 443) { if (port > 0 && port != 80 && port != 443) {
dn.append(QLatin1Char(':')); dn.append(QLatin1Char(':'));
@@ -116,17 +114,6 @@ QString Account::displayName() const
return dn; return dn;
} }
QString Account::davDisplayName() const
{
return _displayName;
}
void Account::setDavDisplayName(const QString &newDisplayName)
{
_displayName = newDisplayName;
emit accountChangedDisplayName();
}
QString Account::id() const QString Account::id() const
{ {
return _id; return _id;
@@ -178,7 +165,7 @@ QUrl Account::davUrl() const
QUrl Account::deprecatedPrivateLinkUrl(const QByteArray &numericFileId) const QUrl Account::deprecatedPrivateLinkUrl(const QByteArray &numericFileId) const
{ {
return Utility::concatUrlPath(_userVisibleUrl, return Utility::concatUrlPath(url(),
QLatin1String("/index.php/f/") + QUrl::toPercentEncoding(QString::fromLatin1(numericFileId))); QLatin1String("/index.php/f/") + QUrl::toPercentEncoding(QString::fromLatin1(numericFileId)));
} }
@@ -313,12 +300,6 @@ void Account::setSslErrorHandler(AbstractSslErrorHandler *handler)
void Account::setUrl(const QUrl &url) void Account::setUrl(const QUrl &url)
{ {
_url = url; _url = url;
_userVisibleUrl = url;
}
void Account::setUserVisibleHost(const QString &host)
{
_userVisibleUrl.setHost(host);
} }
QVariant Account::credentialSetting(const QString &key) const QVariant Account::credentialSetting(const QString &key) const

View File

@@ -26,10 +26,7 @@
#include <QSslCipher> #include <QSslCipher>
#include <QSslError> #include <QSslError>
#include <QSharedPointer> #include <QSharedPointer>
#ifndef TOKEN_AUTH_ONLY
#include <QPixmap> #include <QPixmap>
#endif
#include "common/utility.h" #include "common/utility.h"
#include <memory> #include <memory>
@@ -86,13 +83,8 @@ public:
QString davUser() const; QString davUser() const;
void setDavUser(const QString &newDavUser); void setDavUser(const QString &newDavUser);
QString davDisplayName() const;
void setDavDisplayName(const QString &newDisplayName);
#ifndef TOKEN_AUTH_ONLY
QImage avatar() const; QImage avatar() const;
void setAvatar(const QImage &img); void setAvatar(const QImage &img);
#endif
/// The name of the account as shown in the toolbar /// The name of the account as shown in the toolbar
QString displayName() const; QString displayName() const;
@@ -104,9 +96,6 @@ public:
void setUrl(const QUrl &url); void setUrl(const QUrl &url);
QUrl url() const { return _url; } QUrl url() const { return _url; }
/// Adjusts _userVisibleUrl once the host to use is discovered.
void setUserVisibleHost(const QString &host);
/** /**
* @brief The possibly themed dav path for the account. It has * @brief The possibly themed dav path for the account. It has
* a trailing slash. * a trailing slash.
@@ -220,7 +209,7 @@ public:
/** True when the server supports HTTP2 */ /** True when the server supports HTTP2 */
bool isHttp2Supported() { return _http2Supported; } bool isHttp2Supported() { return _http2Supported; }
void setHttp2Supported(bool value) { _http2Supported = value; } void setHttp2Supported(bool value) { _http2Supported = value; };
void clearCookieJar(); void clearCookieJar();
void lendCookieJarTo(QNetworkAccessManager *guest); void lendCookieJarTo(QNetworkAccessManager *guest);
@@ -257,7 +246,6 @@ signals:
void serverVersionChanged(Account *account, const QString &newVersion, const QString &oldVersion); void serverVersionChanged(Account *account, const QString &newVersion, const QString &oldVersion);
void accountChangedAvatar(); void accountChangedAvatar();
void accountChangedDisplayName();
protected Q_SLOTS: protected Q_SLOTS:
void slotCredentialsFetched(); void slotCredentialsFetched();
@@ -270,21 +258,9 @@ private:
QWeakPointer<Account> _sharedThis; QWeakPointer<Account> _sharedThis;
QString _id; QString _id;
QString _davUser; QString _davUser;
QString _displayName;
#ifndef TOKEN_AUTH_ONLY
QImage _avatarImg; QImage _avatarImg;
#endif
QMap<QString, QVariant> _settingsMap; QMap<QString, QVariant> _settingsMap;
QUrl _url; QUrl _url;
/** If url to use for any user-visible urls.
*
* If the server configures overwritehost this can be different from
* the connection url in _url. We retrieve the visible host through
* the ocs/v1.php/config endpoint in ConnectionValidator.
*/
QUrl _userVisibleUrl;
QList<QSslCertificate> _approvedCerts; QList<QSslCertificate> _approvedCerts;
QSslConfiguration _sslConfiguration; QSslConfiguration _sslConfiguration;
Capabilities _capabilities; Capabilities _capabilities;

View File

@@ -145,9 +145,4 @@ QList<int> Capabilities::httpErrorCodesThatResetFailingChunkedUploads() const
} }
return list; return list;
} }
QString Capabilities::invalidFilenameRegex() const
{
return _capabilities["dav"].toMap()["invalidFilenameRegex"].toString();
}
} }

View File

@@ -105,17 +105,6 @@ public:
*/ */
QList<int> httpErrorCodesThatResetFailingChunkedUploads() const; QList<int> httpErrorCodesThatResetFailingChunkedUploads() const;
/**
* Regex that, if contained in a filename, will result in it not being uploaded.
*
* For servers older than 8.1.0 it defaults to [\\:?*"<>|]
* For servers >= that version, it defaults to the empty regex (the server
* will indicate invalid characters through an upload error)
*
* Note that it just needs to be contained. The regex [ab] is contained in "car".
*/
QString invalidFilenameRegex() const;
private: private:
QVariantMap _capabilities; QVariantMap _capabilities;
}; };

View File

@@ -17,7 +17,7 @@
#include <QLoggingCategory> #include <QLoggingCategory>
#include <QNetworkReply> #include <QNetworkReply>
#include <QNetworkProxyFactory> #include <QNetworkProxyFactory>
#include <QXmlStreamReader> #include <QPixmap>
#include "connectionvalidator.h" #include "connectionvalidator.h"
#include "account.h" #include "account.h"
@@ -247,22 +247,10 @@ void ConnectionValidator::slotAuthSuccess()
void ConnectionValidator::checkServerCapabilities() void ConnectionValidator::checkServerCapabilities()
{ {
// The main flow now needs the capabilities
JsonApiJob *job = new JsonApiJob(_account, QLatin1String("ocs/v1.php/cloud/capabilities"), this); JsonApiJob *job = new JsonApiJob(_account, QLatin1String("ocs/v1.php/cloud/capabilities"), this);
job->setTimeout(timeoutToUseMsec); job->setTimeout(timeoutToUseMsec);
QObject::connect(job, &JsonApiJob::jsonReceived, this, &ConnectionValidator::slotCapabilitiesRecieved); QObject::connect(job, &JsonApiJob::jsonReceived, this, &ConnectionValidator::slotCapabilitiesRecieved);
job->start(); job->start();
// And we'll retrieve the ocs config in parallel
// note that 'this' might be destroyed before the job finishes, so intentionally not parented
auto configJob = new JsonApiJob(_account, QLatin1String("ocs/v1.php/config"));
configJob->setTimeout(timeoutToUseMsec);
auto account = _account; // capturing account by value will make it live long enough
QObject::connect(configJob, &JsonApiJob::jsonReceived, _account.data(),
[=](const QJsonDocument &json) {
ocsConfigReceived(json, account);
});
configJob->start();
} }
void ConnectionValidator::slotCapabilitiesRecieved(const QJsonDocument &json) void ConnectionValidator::slotCapabilitiesRecieved(const QJsonDocument &json)
@@ -280,17 +268,6 @@ void ConnectionValidator::slotCapabilitiesRecieved(const QJsonDocument &json)
fetchUser(); fetchUser();
} }
void ConnectionValidator::ocsConfigReceived(const QJsonDocument &json, AccountPtr account)
{
QString host = json.object().value("ocs").toObject().value("data").toObject().value("host").toString();
if (host.isEmpty()) {
qCWarning(lcConnectionValidator) << "Could not extract 'host' from ocs config reply";
return;
}
qCInfo(lcConnectionValidator) << "Determined user-visible host to be" << host;
account->setUserVisibleHost(host);
}
void ConnectionValidator::fetchUser() void ConnectionValidator::fetchUser()
{ {
JsonApiJob *job = new JsonApiJob(_account, QLatin1String("ocs/v1.php/cloud/user"), this); JsonApiJob *job = new JsonApiJob(_account, QLatin1String("ocs/v1.php/cloud/user"), this);
@@ -332,28 +309,20 @@ void ConnectionValidator::slotUserFetched(const QJsonDocument &json)
QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString(); QString user = json.object().value("ocs").toObject().value("data").toObject().value("id").toString();
if (!user.isEmpty()) { if (!user.isEmpty()) {
_account->setDavUser(user); _account->setDavUser(user);
AvatarJob *job = new AvatarJob(_account, this);
job->setTimeout(20 * 1000);
QObject::connect(job, &AvatarJob::avatarPixmap, this, &ConnectionValidator::slotAvatarImage);
job->start();
} }
QString displayName = json.object().value("ocs").toObject().value("data").toObject().value("display-name").toString();
if (!displayName.isEmpty()) {
_account->setDavDisplayName(displayName);
}
#ifndef TOKEN_AUTH_ONLY
AvatarJob *job = new AvatarJob(_account, this);
job->setTimeout(20 * 1000);
QObject::connect(job, &AvatarJob::avatarPixmap, this, &ConnectionValidator::slotAvatarImage);
job->start();
#else
reportResult(Connected);
#endif
} }
#ifndef TOKEN_AUTH_ONLY
void ConnectionValidator::slotAvatarImage(const QImage &img) void ConnectionValidator::slotAvatarImage(const QImage &img)
{ {
_account->setAvatar(img); _account->setAvatar(img);
reportResult(Connected); reportResult(Connected);
} }
#endif
void ConnectionValidator::reportResult(Status status) void ConnectionValidator::reportResult(Status status)
{ {

View File

@@ -58,9 +58,9 @@ namespace OCC {
| |
+---------------------------+ +---------------------------+
| |
+-> checkServerCapabilities --------------v (in parallel) +-> checkServerCapabilities (cloud/capabilities)
JsonApiJob (cloud/capabilities) JsonApiJob (ocs/v1.php/config) JsonApiJob
| +-> ocsConfigReceived |
+-> slotCapabilitiesRecieved -+ +-> slotCapabilitiesRecieved -+
| |
+-----------------------------------+ +-----------------------------------+
@@ -123,15 +123,12 @@ protected slots:
void slotCapabilitiesRecieved(const QJsonDocument &); void slotCapabilitiesRecieved(const QJsonDocument &);
void slotUserFetched(const QJsonDocument &); void slotUserFetched(const QJsonDocument &);
#ifndef TOKEN_AUTH_ONLY
void slotAvatarImage(const QImage &img); void slotAvatarImage(const QImage &img);
#endif
private: private:
void reportResult(Status status); void reportResult(Status status);
void checkServerCapabilities(); void checkServerCapabilities();
void fetchUser(); void fetchUser();
static void ocsConfigReceived(const QJsonDocument &json, AccountPtr account);
/** Sets the account's server version /** Sets the account's server version
* *

View File

@@ -14,7 +14,6 @@
#include <QLoggingCategory> #include <QLoggingCategory>
#include <QString> #include <QString>
#include <QCoreApplication>
#include "common/asserts.h" #include "common/asserts.h"
#include "creds/abstractcredentials.h" #include "creds/abstractcredentials.h"
@@ -54,15 +53,6 @@ QString AbstractCredentials::keychainKey(const QString &url, const QString &user
QString key = user + QLatin1Char(':') + u; QString key = user + QLatin1Char(':') + u;
if (!accountId.isEmpty()) { if (!accountId.isEmpty()) {
key += QLatin1Char(':') + accountId; key += QLatin1Char(':') + accountId;
#ifdef Q_OS_WIN
// On Windows the credential keys aren't namespaced properly
// by qtkeychain. To work around that we manually add namespacing
// to the generated keys. See #6125.
// It's safe to do that since the key format is changing for 2.4
// anyway to include the account ids. That means old keys can be
// migrated to new namespaced keys on windows for 2.4.
key.prepend(QCoreApplication::applicationName() + "_");
#endif
} }
return key; return key;
} }

View File

@@ -442,38 +442,32 @@ void HttpCredentials::persist()
_account->setCredentialSetting(QLatin1String(isOAuthC), isUsingOAuth()); _account->setCredentialSetting(QLatin1String(isOAuthC), isUsingOAuth());
_account->wantsAccountSaved(_account); _account->wantsAccountSaved(_account);
// write cert if there is one // write cert
if (!_clientSslCertificate.isNull()) { WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName());
WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName()); addSettingsToJob(_account, job);
addSettingsToJob(_account, job); job->setInsecureFallback(false);
job->setInsecureFallback(false); connect(job, &Job::finished, this, &HttpCredentials::slotWriteClientCertPEMJobDone);
connect(job, &Job::finished, this, &HttpCredentials::slotWriteClientCertPEMJobDone); job->setKey(keychainKey(_account->url().toString(), _user + clientCertificatePEMC, _account->id()));
job->setKey(keychainKey(_account->url().toString(), _user + clientCertificatePEMC, _account->id())); job->setBinaryData(_clientSslCertificate.toPem());
job->setBinaryData(_clientSslCertificate.toPem()); job->start();
job->start();
} else {
slotWriteClientCertPEMJobDone();
}
} }
void HttpCredentials::slotWriteClientCertPEMJobDone() void HttpCredentials::slotWriteClientCertPEMJobDone(Job *incomingJob)
{ {
// write ssl key if there is one Q_UNUSED(incomingJob);
if (!_clientSslKey.isNull()) { // write ssl key
WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName()); WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName());
addSettingsToJob(_account, job); addSettingsToJob(_account, job);
job->setInsecureFallback(false); job->setInsecureFallback(false);
connect(job, &Job::finished, this, &HttpCredentials::slotWriteClientKeyPEMJobDone); connect(job, &Job::finished, this, &HttpCredentials::slotWriteClientKeyPEMJobDone);
job->setKey(keychainKey(_account->url().toString(), _user + clientKeyPEMC, _account->id())); job->setKey(keychainKey(_account->url().toString(), _user + clientKeyPEMC, _account->id()));
job->setBinaryData(_clientSslKey.toPem()); job->setBinaryData(_clientSslKey.toPem());
job->start(); job->start();
} else {
slotWriteClientKeyPEMJobDone();
}
} }
void HttpCredentials::slotWriteClientKeyPEMJobDone() void HttpCredentials::slotWriteClientKeyPEMJobDone(Job *incomingJob)
{ {
Q_UNUSED(incomingJob);
WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName()); WritePasswordJob *job = new WritePasswordJob(Theme::instance()->appName());
addSettingsToJob(_account, job); addSettingsToJob(_account, job);
job->setInsecureFallback(false); job->setInsecureFallback(false);

View File

@@ -114,8 +114,8 @@ private Q_SLOTS:
void slotReadClientKeyPEMJobDone(QKeychain::Job *); void slotReadClientKeyPEMJobDone(QKeychain::Job *);
void slotReadJobDone(QKeychain::Job *); void slotReadJobDone(QKeychain::Job *);
void slotWriteClientCertPEMJobDone(); void slotWriteClientCertPEMJobDone(QKeychain::Job *);
void slotWriteClientKeyPEMJobDone(); void slotWriteClientKeyPEMJobDone(QKeychain::Job *);
void slotWriteJobDone(QKeychain::Job *); void slotWriteJobDone(QKeychain::Job *);
protected: protected:

View File

@@ -102,7 +102,7 @@ QString TokenCredentials::password() const
return _password; return _password;
} }
QNetworkAccessManager *TokenCredentials::createQNAM() const QNetworkAccessManager *TokenCredentials::getQNAM() const
{ {
AccessManager *qnam = new TokenCredentialsAccessManager(this); AccessManager *qnam = new TokenCredentialsAccessManager(this);

View File

@@ -40,7 +40,7 @@ public:
TokenCredentials(const QString &user, const QString &password, const QString &token); TokenCredentials(const QString &user, const QString &password, const QString &token);
QString authType() const Q_DECL_OVERRIDE; QString authType() const Q_DECL_OVERRIDE;
QNetworkAccessManager *createQNAM() const Q_DECL_OVERRIDE; QNetworkAccessManager *getQNAM() const Q_DECL_OVERRIDE;
bool ready() const Q_DECL_OVERRIDE; bool ready() const Q_DECL_OVERRIDE;
void askFromUser() Q_DECL_OVERRIDE; void askFromUser() Q_DECL_OVERRIDE;
void fetchFromKeychain() Q_DECL_OVERRIDE; void fetchFromKeychain() Q_DECL_OVERRIDE;

View File

@@ -17,7 +17,6 @@
#include "account.h" #include "account.h"
#include "theme.h" #include "theme.h"
#include "common/asserts.h" #include "common/asserts.h"
#include "common/checksums.h"
#include <csync_private.h> #include <csync_private.h>
#include <csync_rename.h> #include <csync_rename.h>
@@ -301,6 +300,28 @@ void DiscoverySingleDirectoryJob::abort()
} }
} }
/**
* Returns the highest-quality checksum in a 'checksums'
* property retrieved from the server.
*
* Example: "ADLER32:1231 SHA1:ab124124 MD5:2131affa21"
* -> "SHA1:ab124124"
*/
static QByteArray findBestChecksum(const QByteArray &checksums)
{
int i = 0;
// The order of the searches here defines the preference ordering.
if (-1 != (i = checksums.indexOf("SHA1:"))
|| -1 != (i = checksums.indexOf("MD5:"))
|| -1 != (i = checksums.indexOf("Adler32:"))) {
// Now i is the start of the best checksum
// Grab it until the next space or end of string.
auto checksum = checksums.mid(i);
return checksum.mid(0, checksum.indexOf(" "));
}
return QByteArray();
}
static std::unique_ptr<csync_file_stat_t> propertyMapToFileStat(const QMap<QString, QString> &map) static std::unique_ptr<csync_file_stat_t> propertyMapToFileStat(const QMap<QString, QString> &map)
{ {
std::unique_ptr<csync_file_stat_t> file_stat(new csync_file_stat_t); std::unique_ptr<csync_file_stat_t> file_stat(new csync_file_stat_t);

View File

@@ -27,6 +27,7 @@
#include <QTimer> #include <QTimer>
#include <QMutex> #include <QMutex>
#include <QCoreApplication> #include <QCoreApplication>
#include <QPixmap>
#include <QJsonDocument> #include <QJsonDocument>
#include <QJsonObject> #include <QJsonObject>
@@ -625,7 +626,6 @@ bool PropfindJob::finished()
/*********************************************************************************************/ /*********************************************************************************************/
#ifndef TOKEN_AUTH_ONLY
AvatarJob::AvatarJob(AccountPtr account, QObject *parent) AvatarJob::AvatarJob(AccountPtr account, QObject *parent)
: AbstractNetworkJob(account, QString(), parent) : AbstractNetworkJob(account, QString(), parent)
{ {
@@ -656,7 +656,6 @@ bool AvatarJob::finished()
emit(avatarPixmap(avImage)); emit(avatarPixmap(avImage));
return true; return true;
} }
#endif
/*********************************************************************************************/ /*********************************************************************************************/
@@ -820,69 +819,71 @@ bool JsonApiJob::finished()
} }
DetermineAuthTypeJob::DetermineAuthTypeJob(AccountPtr account, QObject *parent) DetermineAuthTypeJob::DetermineAuthTypeJob(AccountPtr account, QObject *parent)
: QObject(parent) : AbstractNetworkJob(account, QString(), parent)
, _account(account) , _redirects(0)
{ {
// This job implements special redirect handling to detect redirections
// to pages that are indicative of Shibboleth-using servers. Hence we
// disable the standard job redirection handling here.
_followRedirects = false;
} }
void DetermineAuthTypeJob::start() void DetermineAuthTypeJob::start()
{ {
qCInfo(lcDetermineAuthTypeJob) << "Determining auth type for" << _account->davUrl(); send(account()->davUrl());
AbstractNetworkJob::start();
}
QNetworkRequest req; bool DetermineAuthTypeJob::finished()
// Prevent HttpCredentialsAccessManager from setting an Authorization header. {
req.setAttribute(HttpCredentials::DontAddCredentialsAttribute, true); QUrl redirection = reply()->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
// Don't reuse previous auth credentials if (_redirects >= maxRedirects()) {
req.setAttribute(QNetworkRequest::AuthenticationReuseAttribute, QNetworkRequest::Manual); redirection.clear();
// Don't send cookies, we can't determine the auth type if we're logged in }
req.setAttribute(QNetworkRequest::CookieLoadControlAttribute, QNetworkRequest::Manual);
// Start two parallel requests, one determines whether it's a shib server auto authChallenge = reply()->rawHeader("WWW-Authenticate").toLower();
// and the other checks the HTTP auth method. if (redirection.isEmpty()) {
auto get = _account->sendRequest("GET", _account->davUrl(), req); if (authChallenge.contains("bearer ")) {
auto propfind = _account->sendRequest("PROPFIND", _account->davUrl(), req); emit authType(OAuth);
get->setTimeout(30 * 1000); } else if (!authChallenge.isEmpty()) {
propfind->setTimeout(30 * 1000); emit authType(Basic);
get->setIgnoreCredentialFailure(true); } else {
propfind->setIgnoreCredentialFailure(true); // This is also where we end up in case of network error.
emit authType(Unknown);
connect(get, &AbstractNetworkJob::redirected, this, [this, get](QNetworkReply *, const QUrl &target, int) { }
} else if (redirection.toString().endsWith(account()->davPath())) {
// do a new run
_redirects++;
resetTimeout();
send(redirection);
qCDebug(lcDetermineAuthTypeJob()) << "Redirected to:" << redirection.toString();
return false; // don't discard
} else {
#ifndef NO_SHIBBOLETH #ifndef NO_SHIBBOLETH
QRegExp shibbolethyWords("SAML|wayf"); QRegExp shibbolethyWords("SAML|wayf");
shibbolethyWords.setCaseSensitivity(Qt::CaseInsensitive); shibbolethyWords.setCaseSensitivity(Qt::CaseInsensitive);
if (target.toString().contains(shibbolethyWords)) { if (redirection.toString().contains(shibbolethyWords)) {
_resultGet = Shibboleth; emit authType(Shibboleth);
get->setFollowRedirects(false); } else
}
#endif #endif
}); {
connect(get, &SimpleNetworkJob::finishedSignal, this, [this]() { // We got redirected to an address that doesn't look like shib
_getDone = true; // and also doesn't have the davPath. Give up.
checkBothDone(); qCWarning(lcDetermineAuthTypeJob()) << account()->davUrl()
}); << "was redirected to the incompatible address"
connect(propfind, &SimpleNetworkJob::finishedSignal, this, [this](QNetworkReply *reply) { << redirection.toString();
auto authChallenge = reply->rawHeader("WWW-Authenticate").toLower(); emit authType(Unknown);
if (authChallenge.contains("bearer ")) {
_resultPropfind = OAuth;
} else if (authChallenge.isEmpty()) {
qCWarning(lcDetermineAuthTypeJob) << "Did not receive WWW-Authenticate reply to auth-test PROPFIND";
} }
_propfindDone = true; }
checkBothDone(); return true;
});
} }
void DetermineAuthTypeJob::checkBothDone() void DetermineAuthTypeJob::send(const QUrl &url)
{ {
if (!_getDone || !_propfindDone) QNetworkRequest req;
return; // Prevent HttpCredentialsAccessManager from setting an Authorization header.
auto result = _resultPropfind; req.setAttribute(HttpCredentials::DontAddCredentialsAttribute, true);
// OAuth > Shib > Basic sendRequest("GET", url, req);
if (_resultGet == Shibboleth && result != OAuth)
result = Shibboleth;
qCInfo(lcDetermineAuthTypeJob) << "Auth type for" << _account->davUrl() << "is" << result;
emit authType(result);
deleteLater();
} }
SimpleNetworkJob::SimpleNetworkJob(AccountPtr account, QObject *parent) SimpleNetworkJob::SimpleNetworkJob(AccountPtr account, QObject *parent)

View File

@@ -133,7 +133,7 @@ private:
QList<QByteArray> _properties; QList<QByteArray> _properties;
}; };
#ifndef TOKEN_AUTH_ONLY
/** /**
* @brief The AvatarJob class * @brief The AvatarJob class
* *
@@ -155,7 +155,7 @@ signals:
* @brief avatarPixmap - returns either a valid pixmap or not. * @brief avatarPixmap - returns either a valid pixmap or not.
*/ */
void avatarPixmap(const QImage &); void avatarPixmap(QImage);
private slots: private slots:
virtual bool finished() Q_DECL_OVERRIDE; virtual bool finished() Q_DECL_OVERRIDE;
@@ -163,7 +163,6 @@ private slots:
private: private:
QUrl _avatarUrl; QUrl _avatarUrl;
}; };
#endif
/** /**
* @brief Send a Proppatch request * @brief Send a Proppatch request
@@ -356,29 +355,26 @@ private:
* @brief Checks with auth type to use for a server * @brief Checks with auth type to use for a server
* @ingroup libsync * @ingroup libsync
*/ */
class OWNCLOUDSYNC_EXPORT DetermineAuthTypeJob : public QObject class OWNCLOUDSYNC_EXPORT DetermineAuthTypeJob : public AbstractNetworkJob
{ {
Q_OBJECT Q_OBJECT
public: public:
enum AuthType { enum AuthType {
Basic, // also the catch-all fallback for backwards compatibility reasons Unknown,
Basic,
OAuth, OAuth,
Shibboleth Shibboleth
}; };
explicit DetermineAuthTypeJob(AccountPtr account, QObject *parent = 0); explicit DetermineAuthTypeJob(AccountPtr account, QObject *parent = 0);
void start(); void start() Q_DECL_OVERRIDE;
signals: signals:
void authType(AuthType); void authType(AuthType);
private slots:
bool finished() Q_DECL_OVERRIDE;
private: private:
void checkBothDone(); void send(const QUrl &url);
int _redirects;
AccountPtr _account;
AuthType _resultGet = Basic;
AuthType _resultPropfind = Basic;
bool _getDone = false;
bool _propfindDone = false;
}; };
/** /**

View File

@@ -114,13 +114,13 @@ PropagateItemJob::~PropagateItemJob()
static qint64 getMinBlacklistTime() static qint64 getMinBlacklistTime()
{ {
return qMax(qEnvironmentVariableIntValue("OWNCLOUD_BLACKLIST_TIME_MIN"), return qMax(qgetenv("OWNCLOUD_BLACKLIST_TIME_MIN").toInt(),
25); // 25 seconds 25); // 25 seconds
} }
static qint64 getMaxBlacklistTime() static qint64 getMaxBlacklistTime()
{ {
int v = qEnvironmentVariableIntValue("OWNCLOUD_BLACKLIST_TIME_MAX"); int v = qgetenv("OWNCLOUD_BLACKLIST_TIME_MAX").toInt();
if (v > 0) if (v > 0)
return v; return v;
return 24 * 60 * 60; // 1 day return 24 * 60 * 60; // 1 day
@@ -742,16 +742,6 @@ PropagatorJob::JobParallelism PropagatorCompositeJob::parallelism()
return FullParallelism; return FullParallelism;
} }
void PropagatorCompositeJob::slotSubJobAbortFinished()
{
// Count that job has been finished
_abortsCount--;
// Emit abort if last job has been aborted
if (_abortsCount == 0) {
emit abortFinished();
}
}
bool PropagatorCompositeJob::scheduleSelfOrChild() bool PropagatorCompositeJob::scheduleSelfOrChild()
{ {
@@ -910,8 +900,7 @@ void PropagateDirectory::slotFirstJobFinished(SyncFileItem::Status status)
if (status != SyncFileItem::Success && status != SyncFileItem::Restoration) { if (status != SyncFileItem::Success && status != SyncFileItem::Restoration) {
if (_state != Finished) { if (_state != Finished) {
// Synchronously abort abort();
abort(AbortType::Synchronous);
_state = Finished; _state = Finished;
emit finished(status); emit finished(status);
} }

View File

@@ -65,11 +65,6 @@ class PropagatorJob : public QObject
public: public:
explicit PropagatorJob(OwncloudPropagator *propagator); explicit PropagatorJob(OwncloudPropagator *propagator);
enum AbortType {
Synchronous,
Asynchronous
};
enum JobState { enum JobState {
NotYetStarted, NotYetStarted,
Running, Running,
@@ -103,14 +98,7 @@ public:
virtual qint64 committedDiskSpace() const { return 0; } virtual qint64 committedDiskSpace() const { return 0; }
public slots: public slots:
/* virtual void abort() {}
* Asynchronous abort requires emit of abortFinished() signal,
* while synchronous is expected to abort immedietaly.
*/
virtual void abort(PropagatorJob::AbortType abortType) {
if (abortType == AbortType::Asynchronous)
emit abortFinished();
}
/** Starts this job, or a new subjob /** Starts this job, or a new subjob
* returns true if a job was started. * returns true if a job was started.
@@ -122,14 +110,11 @@ signals:
*/ */
void finished(SyncFileItem::Status); void finished(SyncFileItem::Status);
/**
* Emitted when the abort is fully finished
*/
void abortFinished(SyncFileItem::Status status = SyncFileItem::NormalError);
protected: protected:
OwncloudPropagator *propagator() const; OwncloudPropagator *propagator() const;
}; };
/* /*
* Abstract class to propagate a single item * Abstract class to propagate a single item
*/ */
@@ -200,11 +185,10 @@ public:
SyncFileItemVector _tasksToDo; SyncFileItemVector _tasksToDo;
QVector<PropagatorJob *> _runningJobs; QVector<PropagatorJob *> _runningJobs;
SyncFileItem::Status _hasError; // NoStatus, or NormalError / SoftError if there was an error SyncFileItem::Status _hasError; // NoStatus, or NormalError / SoftError if there was an error
quint64 _abortsCount;
explicit PropagatorCompositeJob(OwncloudPropagator *propagator) explicit PropagatorCompositeJob(OwncloudPropagator *propagator)
: PropagatorJob(propagator) : PropagatorJob(propagator)
, _hasError(SyncFileItem::NoStatus), _abortsCount(0) , _hasError(SyncFileItem::NoStatus)
{ {
} }
@@ -225,32 +209,15 @@ public:
virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE; virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE;
virtual JobParallelism parallelism() Q_DECL_OVERRIDE; virtual JobParallelism parallelism() Q_DECL_OVERRIDE;
virtual void abort() Q_DECL_OVERRIDE
/*
* Abort synchronously or asynchronously - some jobs
* require to be finished without immediete abort (abort on job might
* cause conflicts/duplicated files - owncloud/client/issues/5949)
*/
virtual void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE
{ {
if (!_runningJobs.empty()) { foreach (PropagatorJob *j, _runningJobs)
_abortsCount = _runningJobs.size(); j->abort();
foreach (PropagatorJob *j, _runningJobs) {
if (abortType == AbortType::Asynchronous) {
connect(j, &PropagatorJob::abortFinished,
this, &PropagatorCompositeJob::slotSubJobAbortFinished);
}
j->abort(abortType);
}
} else if (abortType == AbortType::Asynchronous){
emit abortFinished();
}
} }
qint64 committedDiskSpace() const Q_DECL_OVERRIDE; qint64 committedDiskSpace() const Q_DECL_OVERRIDE;
private slots: private slots:
void slotSubJobAbortFinished();
bool possiblyRunNextJob(PropagatorJob *next) bool possiblyRunNextJob(PropagatorJob *next)
{ {
if (next->_state == NotYetStarted) { if (next->_state == NotYetStarted) {
@@ -291,17 +258,11 @@ public:
virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE; virtual bool scheduleSelfOrChild() Q_DECL_OVERRIDE;
virtual JobParallelism parallelism() Q_DECL_OVERRIDE; virtual JobParallelism parallelism() Q_DECL_OVERRIDE;
virtual void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE virtual void abort() Q_DECL_OVERRIDE
{ {
if (_firstJob) if (_firstJob)
// Force first job to abort synchronously _firstJob->abort();
// even if caller allows async abort (asyncAbort) _subJobs.abort();
_firstJob->abort(AbortType::Synchronous);
if (abortType == AbortType::Asynchronous){
connect(&_subJobs, &PropagatorCompositeJob::abortFinished, this, &PropagateDirectory::abortFinished);
}
_subJobs.abort(abortType);
} }
void increaseAffectedCount() void increaseAffectedCount()
@@ -319,7 +280,6 @@ private slots:
void slotFirstJobFinished(SyncFileItem::Status status); void slotFirstJobFinished(SyncFileItem::Status status);
void slotSubJobsFinished(SyncFileItem::Status status); void slotSubJobsFinished(SyncFileItem::Status status);
}; };
@@ -364,7 +324,6 @@ public:
, _chunkSize(10 * 1000 * 1000) // 10 MB, overridden in setSyncOptions , _chunkSize(10 * 1000 * 1000) // 10 MB, overridden in setSyncOptions
, _account(account) , _account(account)
{ {
qRegisterMetaType<PropagatorJob::AbortType>("PropagatorJob::AbortType");
} }
~OwncloudPropagator(); ~OwncloudPropagator();
@@ -445,23 +404,13 @@ public:
void abort() void abort()
{ {
bool alreadyAborting = _abortRequested.fetchAndStoreOrdered(true); _abortRequested.fetchAndStoreOrdered(true);
if (alreadyAborting)
return;
if (_rootJob) { if (_rootJob) {
// Connect to abortFinished which signals that abort has been asynchronously finished // We're possibly already in an item's finished stack
connect(_rootJob.data(), &PropagateDirectory::abortFinished, this, &OwncloudPropagator::emitFinished); QMetaObject::invokeMethod(_rootJob.data(), "abort", Qt::QueuedConnection);
// Use Queued Connection because we're possibly already in an item's finished stack
QMetaObject::invokeMethod(_rootJob.data(), "abort", Qt::QueuedConnection,
Q_ARG(PropagatorJob::AbortType, PropagatorJob::AbortType::Asynchronous));
// Give asynchronous abort 5000 msec to finish on its own
QTimer::singleShot(5000, this, SLOT(abortTimeout()));
} else {
// No root job, call emitFinished
emitFinished(SyncFileItem::NormalError);
} }
// abort() of all jobs will likely have already resulted in finished being emitted, but just in case.
QMetaObject::invokeMethod(this, "emitFinished", Qt::QueuedConnection, Q_ARG(SyncFileItem::Status, SyncFileItem::NormalError));
} }
// timeout in seconds // timeout in seconds
@@ -482,13 +431,6 @@ public:
private slots: private slots:
void abortTimeout()
{
// Abort synchronously and finish
_rootJob.data()->abort(PropagatorJob::AbortType::Synchronous);
emitFinished(SyncFileItem::NormalError);
}
/** Emit the finished signal and make sure it is only emitted once */ /** Emit the finished signal and make sure it is only emitted once */
void emitFinished(SyncFileItem::Status status) void emitFinished(SyncFileItem::Status status)
{ {

View File

@@ -127,6 +127,7 @@ void GETFileJob::start()
sendRequest("GET", _directDownloadUrl, req); sendRequest("GET", _directDownloadUrl, req);
} }
reply()->setReadBufferSize(16 * 1024); // keep low so we can easier limit the bandwidth
qCDebug(lcGetJob) << _bandwidthManager << _bandwidthChoked << _bandwidthLimited; qCDebug(lcGetJob) << _bandwidthManager << _bandwidthChoked << _bandwidthLimited;
if (_bandwidthManager) { if (_bandwidthManager) {
_bandwidthManager->registerDownloadJob(this); _bandwidthManager->registerDownloadJob(this);
@@ -136,20 +137,14 @@ void GETFileJob::start()
qCWarning(lcGetJob) << " Network error: " << errorString(); qCWarning(lcGetJob) << " Network error: " << errorString();
} }
connect(reply(), &QNetworkReply::metaDataChanged, this, &GETFileJob::slotMetaDataChanged);
connect(reply(), &QIODevice::readyRead, this, &GETFileJob::slotReadyRead);
connect(reply(), &QNetworkReply::downloadProgress, this, &GETFileJob::downloadProgress);
connect(this, &AbstractNetworkJob::networkActivity, account().data(), &Account::propagatorNetworkActivity); connect(this, &AbstractNetworkJob::networkActivity, account().data(), &Account::propagatorNetworkActivity);
AbstractNetworkJob::start(); AbstractNetworkJob::start();
} }
void GETFileJob::newReplyHook(QNetworkReply *reply)
{
reply->setReadBufferSize(16 * 1024); // keep low so we can easier limit the bandwidth
connect(reply, &QNetworkReply::metaDataChanged, this, &GETFileJob::slotMetaDataChanged);
connect(reply, &QIODevice::readyRead, this, &GETFileJob::slotReadyRead);
connect(reply, &QNetworkReply::downloadProgress, this, &GETFileJob::downloadProgress);
}
void GETFileJob::slotMetaDataChanged() void GETFileJob::slotMetaDataChanged()
{ {
// For some reason setting the read buffer in GETFileJob::start doesn't seem to go // For some reason setting the read buffer in GETFileJob::start doesn't seem to go
@@ -158,10 +153,6 @@ void GETFileJob::slotMetaDataChanged()
int httpStatus = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); int httpStatus = reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
// Ignore redirects
if (httpStatus == 301 || httpStatus == 302 || httpStatus == 303 || httpStatus == 307 || httpStatus == 308)
return;
// If the status code isn't 2xx, don't write the reply body to the file. // If the status code isn't 2xx, don't write the reply body to the file.
// For any error: handle it when the job is finished, not here. // For any error: handle it when the job is finished, not here.
if (httpStatus / 100 != 2) { if (httpStatus / 100 != 2) {
@@ -225,8 +216,6 @@ void GETFileJob::slotMetaDataChanged()
if (!lastModified.isNull()) { if (!lastModified.isNull()) {
_lastModified = Utility::qDateTimeToTime_t(lastModified.toDateTime()); _lastModified = Utility::qDateTimeToTime_t(lastModified.toDateTime());
} }
_saveBodyToFile = true;
} }
void GETFileJob::setBandwidthManager(BandwidthManager *bwm) void GETFileJob::setBandwidthManager(BandwidthManager *bwm)
@@ -292,7 +281,7 @@ void GETFileJob::slotReadyRead()
return; return;
} }
if (_device->isOpen() && _saveBodyToFile) { if (_device->isOpen()) {
qint64 w = _device->write(buffer.constData(), r); qint64 w = _device->write(buffer.constData(), r);
if (w != r) { if (w != r) {
_errorString = _device->errorString(); _errorString = _device->errorString();
@@ -357,16 +346,13 @@ void PropagateDownloadFile::start()
} }
} }
// If we have a conflict where size of the file is unchanged, // If we have a conflict where size and mtime are identical,
// compare the remote checksum to the local one. // compare the remote checksum to the local one.
// Maybe it's not a real conflict and no download is necessary! // Maybe it's not a real conflict and no download is necessary!
// If the hashes are collision safe and identical, we assume the content is too.
// For weak checksums, we only do that if the mtimes are also identical.
if (_item->_instruction == CSYNC_INSTRUCTION_CONFLICT if (_item->_instruction == CSYNC_INSTRUCTION_CONFLICT
&& _item->_size == _item->_previousSize && _item->_size == _item->_previousSize
&& !_item->_checksumHeader.isEmpty() && _item->_modtime == _item->_previousModtime
&& (csync_is_collision_safe_hash(_item->_checksumHeader) && !_item->_checksumHeader.isEmpty()) {
|| _item->_modtime == _item->_previousModtime)) {
qCDebug(lcPropagateDownload) << _item->_file << "may not need download, computing checksum"; qCDebug(lcPropagateDownload) << _item->_file << "may not need download, computing checksum";
auto computeChecksum = new ComputeChecksum(this); auto computeChecksum = new ComputeChecksum(this);
computeChecksum->setChecksumType(parseChecksumHeaderType(_item->_checksumHeader)); computeChecksum->setChecksumType(parseChecksumHeaderType(_item->_checksumHeader));
@@ -382,17 +368,8 @@ void PropagateDownloadFile::start()
void PropagateDownloadFile::conflictChecksumComputed(const QByteArray &checksumType, const QByteArray &checksum) void PropagateDownloadFile::conflictChecksumComputed(const QByteArray &checksumType, const QByteArray &checksum)
{ {
if (makeChecksumHeader(checksumType, checksum) == _item->_checksumHeader) { if (makeChecksumHeader(checksumType, checksum) == _item->_checksumHeader) {
// No download necessary, just update fs and journal metadata
qCDebug(lcPropagateDownload) << _item->_file << "remote and local checksum match"; qCDebug(lcPropagateDownload) << _item->_file << "remote and local checksum match";
// No download necessary, just update metadata
// Apply the server mtime locally if necessary, ensuring the journal
// and local mtimes end up identical
auto fn = propagator()->getFilePath(_item->_file);
if (_item->_modtime != _item->_previousModtime) {
FileSystem::setModTime(fn, _item->_modtime);
emit propagator()->touchedFile(fn);
}
_item->_modtime = FileSystem::getModTime(fn);
updateMetadata(/*isConflict=*/false); updateMetadata(/*isConflict=*/false);
return; return;
} }
@@ -647,10 +624,7 @@ void PropagateDownloadFile::slotGetFinished()
this, &PropagateDownloadFile::transmissionChecksumValidated); this, &PropagateDownloadFile::transmissionChecksumValidated);
connect(validator, &ValidateChecksumHeader::validationFailed, connect(validator, &ValidateChecksumHeader::validationFailed,
this, &PropagateDownloadFile::slotChecksumFail); this, &PropagateDownloadFile::slotChecksumFail);
auto checksumHeader = findBestChecksum(job->reply()->rawHeader(checkSumHeaderC)); auto checksumHeader = job->reply()->rawHeader(checkSumHeaderC);
auto contentMd5Header = job->reply()->rawHeader(contentMd5HeaderC);
if (checksumHeader.isEmpty() && !contentMd5Header.isEmpty())
checksumHeader = "MD5:" + contentMd5Header;
validator->start(_tmpFile.fileName(), checksumHeader); validator->start(_tmpFile.fileName(), checksumHeader);
} }
@@ -923,13 +897,9 @@ void PropagateDownloadFile::slotDownloadProgress(qint64 received, qint64)
} }
void PropagateDownloadFile::abort(PropagatorJob::AbortType abortType) void PropagateDownloadFile::abort()
{ {
if (_job && _job->reply()) if (_job && _job->reply())
_job->reply()->abort(); _job->reply()->abort();
if (abortType == AbortType::Asynchronous) {
emit abortFinished();
}
} }
} }

View File

@@ -43,9 +43,6 @@ class GETFileJob : public AbstractNetworkJob
bool _hasEmittedFinishedSignal; bool _hasEmittedFinishedSignal;
time_t _lastModified; time_t _lastModified;
/// Will be set to true once we've seen a 2xx response header
bool _saveBodyToFile = false;
public: public:
// DOES NOT take ownership of the device. // DOES NOT take ownership of the device.
explicit GETFileJob(AccountPtr account, const QString &path, QFile *device, explicit GETFileJob(AccountPtr account, const QString &path, QFile *device,
@@ -79,8 +76,6 @@ public:
} }
} }
void newReplyHook(QNetworkReply *reply) override;
void setBandwidthManager(BandwidthManager *bwm); void setBandwidthManager(BandwidthManager *bwm);
void setChoked(bool c); void setChoked(bool c);
void setBandwidthLimited(bool b); void setBandwidthLimited(bool b);
@@ -190,7 +185,7 @@ private slots:
/// Called when it's time to update the db metadata /// Called when it's time to update the db metadata
void updateMetadata(bool isConflict); void updateMetadata(bool isConflict);
void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE;
void slotDownloadProgress(qint64, qint64); void slotDownloadProgress(qint64, qint64);
void slotChecksumFail(const QString &errMsg); void slotChecksumFail(const QString &errMsg);

View File

@@ -75,14 +75,10 @@ void PropagateRemoteDelete::start()
_job->start(); _job->start();
} }
void PropagateRemoteDelete::abort(PropagatorJob::AbortType abortType) void PropagateRemoteDelete::abort()
{ {
if (_job && _job->reply()) if (_job && _job->reply())
_job->reply()->abort(); _job->reply()->abort();
if (abortType == AbortType::Asynchronous) {
emit abortFinished();
}
} }
void PropagateRemoteDelete::slotDeleteJobFinished() void PropagateRemoteDelete::slotDeleteJobFinished()

View File

@@ -52,7 +52,7 @@ public:
{ {
} }
void start() Q_DECL_OVERRIDE; void start() Q_DECL_OVERRIDE;
void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE;
bool isLikelyFinishedQuickly() Q_DECL_OVERRIDE { return !_item->isDirectory(); } bool isLikelyFinishedQuickly() Q_DECL_OVERRIDE { return !_item->isDirectory(); }

View File

@@ -60,14 +60,10 @@ void PropagateRemoteMkdir::slotStartMkcolJob()
_job->start(); _job->start();
} }
void PropagateRemoteMkdir::abort(PropagatorJob::AbortType abortType) void PropagateRemoteMkdir::abort()
{ {
if (_job && _job->reply()) if (_job && _job->reply())
_job->reply()->abort(); _job->reply()->abort();
if (abortType == AbortType::Asynchronous) {
emit abortFinished();
}
} }
void PropagateRemoteMkdir::setDeleteExisting(bool enabled) void PropagateRemoteMkdir::setDeleteExisting(bool enabled)

View File

@@ -35,7 +35,7 @@ public:
{ {
} }
void start() Q_DECL_OVERRIDE; void start() Q_DECL_OVERRIDE;
void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE;
// Creating a directory should be fast. // Creating a directory should be fast.
bool isLikelyFinishedQuickly() Q_DECL_OVERRIDE { return true; } bool isLikelyFinishedQuickly() Q_DECL_OVERRIDE { return true; }

View File

@@ -117,14 +117,10 @@ void PropagateRemoteMove::start()
_job->start(); _job->start();
} }
void PropagateRemoteMove::abort(PropagatorJob::AbortType abortType) void PropagateRemoteMove::abort()
{ {
if (_job && _job->reply()) if (_job && _job->reply())
_job->reply()->abort(); _job->reply()->abort();
if (abortType == AbortType::Asynchronous) {
emit abortFinished();
}
} }
void PropagateRemoteMove::slotMoveJobFinished() void PropagateRemoteMove::slotMoveJobFinished()

View File

@@ -56,7 +56,7 @@ public:
{ {
} }
void start() Q_DECL_OVERRIDE; void start() Q_DECL_OVERRIDE;
void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE;
JobParallelism parallelism() Q_DECL_OVERRIDE { return _item->isDirectory() ? WaitForFinished : FullParallelism; } JobParallelism parallelism() Q_DECL_OVERRIDE { return _item->isDirectory() ? WaitForFinished : FullParallelism; }
/** /**

View File

@@ -558,24 +558,20 @@ void PropagateUploadFileCommon::slotJobDestroyed(QObject *job)
_jobs.erase(std::remove(_jobs.begin(), _jobs.end(), job), _jobs.end()); _jobs.erase(std::remove(_jobs.begin(), _jobs.end(), job), _jobs.end());
} }
void PropagateUploadFileCommon::abort(PropagatorJob::AbortType abortType) void PropagateUploadFileCommon::abort()
{ {
foreach (auto *job, _jobs) { foreach (auto *job, _jobs) {
if (job->reply()) { if (job->reply()) {
job->reply()->abort(); job->reply()->abort();
} }
} }
if (abortType == AbortType::Asynchronous) {
emit abortFinished();
}
} }
// This function is used whenever there is an error occuring and jobs might be in progress // This function is used whenever there is an error occuring and jobs might be in progress
void PropagateUploadFileCommon::abortWithError(SyncFileItem::Status status, const QString &error) void PropagateUploadFileCommon::abortWithError(SyncFileItem::Status status, const QString &error)
{ {
_finished = true; _finished = true;
abort(AbortType::Synchronous); abort();
done(status, error); done(status, error);
} }
@@ -629,33 +625,4 @@ void PropagateUploadFileCommon::finalize()
done(SyncFileItem::Success); done(SyncFileItem::Success);
} }
void PropagateUploadFileCommon::prepareAbort(PropagatorJob::AbortType abortType) {
if (!_jobs.empty()) {
// Count number of jobs to be aborted asynchronously
_abortCount = _jobs.size();
foreach (AbstractNetworkJob *job, _jobs) {
// Check if async abort is requested
if (job->reply() && abortType == AbortType::Asynchronous) {
// Connect to finished signal of job reply
// to asynchonously finish the abort
connect(job->reply(), &QNetworkReply::finished, this, &PropagateUploadFileCommon::slotReplyAbortFinished);
}
}
} else if (abortType == AbortType::Asynchronous) {
// Empty job list, emit abortFinished immedietaly
emit abortFinished();
}
}
void PropagateUploadFileCommon::slotReplyAbortFinished()
{
_abortCount--;
if (_abortCount == 0) {
emit abortFinished();
}
}
} }

View File

@@ -129,11 +129,6 @@ public:
return true; return true;
} }
QIODevice *device()
{
return _device;
}
QString errorString() QString errorString()
{ {
return _errorString.isEmpty() ? AbstractNetworkJob::errorString() : _errorString; return _errorString.isEmpty() ? AbstractNetworkJob::errorString() : _errorString;
@@ -210,7 +205,6 @@ protected:
QVector<AbstractNetworkJob *> _jobs; /// network jobs that are currently in transit QVector<AbstractNetworkJob *> _jobs; /// network jobs that are currently in transit
bool _finished BITFIELD(1); /// Tells that all the jobs have been finished bool _finished BITFIELD(1); /// Tells that all the jobs have been finished
bool _deleteExisting BITFIELD(1); bool _deleteExisting BITFIELD(1);
quint64 _abortCount; /// Keep track of number of aborted items
// measure the performance of checksum calc and upload // measure the performance of checksum calc and upload
#ifdef WITH_TESTING #ifdef WITH_TESTING
@@ -224,7 +218,6 @@ public:
: PropagateItemJob(propagator, item) : PropagateItemJob(propagator, item)
, _finished(false) , _finished(false)
, _deleteExisting(false) , _deleteExisting(false)
, _abortCount(0)
{ {
} }
@@ -255,20 +248,13 @@ public:
void abortWithError(SyncFileItem::Status status, const QString &error); void abortWithError(SyncFileItem::Status status, const QString &error);
public slots: public slots:
void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE; void abort() Q_DECL_OVERRIDE;
void slotJobDestroyed(QObject *job); void slotJobDestroyed(QObject *job);
private slots: private slots:
void slotReplyAbortFinished();
void slotPollFinished(); void slotPollFinished();
protected: protected:
/**
* Prepares the abort e.g. connects proper signals and slots
* to the subjobs to abort asynchronously
*/
void prepareAbort(PropagatorJob::AbortType abortType);
/** /**
* Checks whether the current error is one that should reset the whole * Checks whether the current error is one that should reset the whole
* transfer if it happens too often. If so: Bump UploadInfo::errorCount * transfer if it happens too often. If so: Bump UploadInfo::errorCount
@@ -301,15 +287,15 @@ private:
* In the non-resuming case it is 0. * In the non-resuming case it is 0.
* If we are resuming, this is the first chunk we need to send * If we are resuming, this is the first chunk we need to send
*/ */
int _startChunk = 0; int _startChunk;
/** /**
* This is the next chunk that we need to send. Starting from 0 even if _startChunk != 0 * This is the next chunk that we need to send. Starting from 0 even if _startChunk != 0
* (In other words, _startChunk + _currentChunk is really the number of the chunk we need to send next) * (In other words, _startChunk + _currentChunk is really the number of the chunk we need to send next)
* (In other words, _currentChunk is the number of the chunk that we already sent or started sending) * (In other words, _currentChunk is the number of the chunk that we already sent or started sending)
*/ */
int _currentChunk = 0; int _currentChunk;
int _chunkCount = 0; /// Total number of chunks for this file int _chunkCount; /// Total number of chunks for this file
int _transferId = 0; /// transfer id (part of the url) int _transferId; /// transfer id (part of the url)
quint64 chunkSize() const { quint64 chunkSize() const {
// Old chunking does not use dynamic chunking algorithm, and does not adjusts the chunk size respectively, // Old chunking does not use dynamic chunking algorithm, and does not adjusts the chunk size respectively,
@@ -317,6 +303,7 @@ private:
return propagator()->syncOptions()._initialChunkSize; return propagator()->syncOptions()._initialChunkSize;
} }
public: public:
PropagateUploadFileV1(OwncloudPropagator *propagator, const SyncFileItemPtr &item) PropagateUploadFileV1(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
: PropagateUploadFileCommon(propagator, item) : PropagateUploadFileCommon(propagator, item)
@@ -324,8 +311,7 @@ public:
} }
void doStartUpload() Q_DECL_OVERRIDE; void doStartUpload() Q_DECL_OVERRIDE;
public slots:
void abort(PropagatorJob::AbortType abortType) Q_DECL_OVERRIDE;
private slots: private slots:
void startNextChunk(); void startNextChunk();
void slotPutFinished(); void slotPutFinished();
@@ -342,11 +328,11 @@ class PropagateUploadFileNG : public PropagateUploadFileCommon
{ {
Q_OBJECT Q_OBJECT
private: private:
quint64 _sent = 0; /// amount of data (bytes) that was already sent quint64 _sent; /// amount of data (bytes) that was already sent
uint _transferId = 0; /// transfer id (part of the url) uint _transferId; /// transfer id (part of the url)
int _currentChunk = 0; /// Id of the next chunk that will be sent int _currentChunk; /// Id of the next chunk that will be sent
quint64 _currentChunkSize = 0; /// current chunk size quint64 _currentChunkSize; /// current chunk size
bool _removeJobError = false; /// If not null, there was an error removing the job bool _removeJobError; /// If not null, there was an error removing the job
// Map chunk number with its size from the PROPFIND on resume. // Map chunk number with its size from the PROPFIND on resume.
// (Only used from slotPropfindIterate/slotPropfindFinished because the LsColJob use signals to report data.) // (Only used from slotPropfindIterate/slotPropfindFinished because the LsColJob use signals to report data.)
@@ -366,6 +352,7 @@ private:
public: public:
PropagateUploadFileNG(OwncloudPropagator *propagator, const SyncFileItemPtr &item) PropagateUploadFileNG(OwncloudPropagator *propagator, const SyncFileItemPtr &item)
: PropagateUploadFileCommon(propagator, item) : PropagateUploadFileCommon(propagator, item)
, _currentChunkSize(0)
{ {
} }
@@ -374,8 +361,6 @@ public:
private: private:
void startNewUpload(); void startNewUpload();
void startNextChunk(); void startNextChunk();
public slots:
void abort(AbortType abortType) Q_DECL_OVERRIDE;
private slots: private slots:
void slotPropfindFinished(); void slotPropfindFinished();
void slotPropfindFinishedWithError(); void slotPropfindFinishedWithError();

View File

@@ -365,7 +365,7 @@ void PropagateUploadFileNG::slotPutFinished()
// target duration for each chunk upload. // target duration for each chunk upload.
double targetDuration = propagator()->syncOptions()._targetChunkUploadDuration; double targetDuration = propagator()->syncOptions()._targetChunkUploadDuration;
if (targetDuration > 0) { if (targetDuration > 0) {
double uploadTime = job->msSinceStart() + 1; // add one to avoid div-by-zero double uploadTime = job->msSinceStart();
auto predictedGoodSize = static_cast<quint64>( auto predictedGoodSize = static_cast<quint64>(
_currentChunkSize / uploadTime * targetDuration); _currentChunkSize / uploadTime * targetDuration);
@@ -491,26 +491,4 @@ void PropagateUploadFileNG::slotUploadProgress(qint64 sent, qint64 total)
} }
propagator()->reportProgress(*_item, _sent + sent - total); propagator()->reportProgress(*_item, _sent + sent - total);
} }
void PropagateUploadFileNG::abort(PropagatorJob::AbortType abortType)
{
// Prepare abort
prepareAbort(abortType);
// Abort all jobs (if there are any left), except final PUT
foreach (AbstractNetworkJob *job, _jobs) {
if (job->reply()) {
if (abortType == AbortType::Asynchronous && qobject_cast<MoveJob *>(job)){
// If it is async abort, dont abort
// MoveJob since it might result in conflict,
// only PUT and MKDIR jobs can be safely aborted.
continue;
}
// Abort the job
job->reply()->abort();
}
}
}
} }

View File

@@ -350,31 +350,4 @@ void PropagateUploadFileV1::slotUploadProgress(qint64 sent, qint64 total)
} }
propagator()->reportProgress(*_item, amount); propagator()->reportProgress(*_item, amount);
} }
void PropagateUploadFileV1::abort(PropagatorJob::AbortType abortType)
{
// Prepare abort
prepareAbort(abortType);
// Abort all jobs (if there are any left), except final PUT
foreach (AbstractNetworkJob *job, _jobs) {
if (job->reply()) {
// If asynchronous abort allowed,
// dont abort final PUT which uploaded its data,
// since this might result in conflicts
if (PUTFileJob *putJob = qobject_cast<PUTFileJob *>(job)){
if (abortType == AbortType::Asynchronous
&& _chunkCount > 0
&& (((_currentChunk + _startChunk) % _chunkCount) == 0)
&& putJob->device()->atEnd()) {
continue;
}
}
// Abort the job
job->reply()->abort();
}
}
}
} }

View File

@@ -25,7 +25,6 @@ namespace OCC {
* It's here for being shared between Upload- and Download Job * It's here for being shared between Upload- and Download Job
*/ */
static const char checkSumHeaderC[] = "OC-Checksum"; static const char checkSumHeaderC[] = "OC-Checksum";
static const char contentMd5HeaderC[] = "Content-MD5";
/** /**
* @brief Declaration of the other propagation jobs * @brief Declaration of the other propagation jobs

Some files were not shown because too many files have changed in this diff Show More