diff --git a/resources/tomboynotes/CMakeLists.txt b/resources/tomboynotes/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/CMakeLists.txt @@ -0,0 +1,125 @@ +cmake_minimum_required(VERSION 3.1) + +project(tomboynotes) + +############ ECM setup ########### +find_package(ECM 5.13.0 CONFIG REQUIRED) + +set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules ${ECM_MODULE_PATH} ${CMAKE_MODULE_PATH}) + +include(FeatureSummary) +include(KDEInstallDirs) +include(KDECMakeSettings) +include(KDEFrameworkCompilerSettings) +include(ECMQtDeclareLoggingCategory) + +########### Dependencies ########### + +set(KF5_VERSION "5.13.0") +set(AKONADI_VERSION "5.0") +set(QT_REQUIRED_VERSION "5.3.0") + +find_package(Qt5 ${QT_REQUIRED_VERSION} REQUIRED Core Network Gui) + +find_package(KF5Akonadi ${AKONADI_MIN_VERSION} CONFIG REQUIRED) +find_package(KF5Config ${KF5_VERSION} CONFIG REQUIRED) +find_package(KF5CoreAddons REQUIRED) +find_package(KF5KIO ${KF5_VERSION} CONFIG REQUIRED) +find_package(KF5Mime REQUIRED) +find_package(KF5WindowSystem REQUIRED) + +find_program(XSLTPROC_EXECUTABLE xsltproc DOC "Path to xslt executable") + +if(XSLTPROC_EXECUTABLE) + # We depend on kdepimlibs, make sure it's found + if(NOT DEFINED KF5Akonadi_DATA_DIR) + find_package(KF5Akonadi REQUIRED) + endif() + + # Macro to generate a D-Bus interface description from a KConfigXT file + macro(kcfg_generate_dbus_interface _kcfg _name) + add_custom_command( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${_name}.xml + COMMAND ${XSLTPROC_EXECUTABLE} --stringparam interfaceName ${_name} + ${KF5Akonadi_DATA_DIR}/kcfg2dbus.xsl + ${_kcfg} + > ${CMAKE_CURRENT_BINARY_DIR}/${_name}.xml + DEPENDS ${KF5Akonadi_DATA_DIR}/kcfg2dbus.xsl + ${_kcfg} + ) + endmacro() +endif() + +remove_definitions(-DQT_NO_URL_CAST_FROM_STRING + -DQT_NO_CAST_FROM_BYTEARRAY + -DQT_USE_QSTRINGBUILDER + -DQT_USE_FAST_OPERATOR_PLUS +) + + + +########### next target ############### + +set(tomboynotesresource_SRCS + configdialog.cpp + tomboynotesresource.cpp + tomboycollectionsdownloadjob.cpp + tomboyitemdownloadjob.cpp + tomboyitemuploadjob.cpp + tomboyitemsdownloadjob.cpp + tomboyjobbase.cpp + tomboyserverauthenticatejob.cpp +) + +ecm_qt_declare_logging_category(tomboynotesresource_SRCS + HEADER debug.h + IDENTIFIER log_tomboynotesresource + CATEGORY_NAME log_tomboynotesresource +) + +ki18n_wrap_ui(tomboynotesresource_SRCS configdialog.ui) + +kconfig_add_kcfg_files(tomboynotesresource_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/settings.kcfgc +) + +kcfg_generate_dbus_interface( + ${CMAKE_CURRENT_SOURCE_DIR}/tomboynotesresource.kcfg + org.kde.Akonadi.TomboyNotes.Settings +) + +qt5_add_dbus_adaptor(tomboynotesresource_SRCS + ${CMAKE_CURRENT_BINARY_DIR}/org.kde.Akonadi.TomboyNotes.Settings.xml + ${CMAKE_CURRENT_BINARY_DIR}/settings.h + Settings +) + + +add_executable(akonadi_tomboynotes_resource ${tomboynotesresource_SRCS}) +target_link_libraries(akonadi_tomboynotes_resource + o2 + Qt5::DBus + Qt5::Gui + Qt5::Network + KF5::AkonadiAgentBase + KF5::ConfigCore + KF5::ConfigWidgets + KF5::CoreAddons + KF5::I18n + KF5::KIOCore + KF5::KIOFileWidgets + KF5::KIONTLM + KF5::KIOWidgets + KF5::Mime + KF5::WindowSystem +) + +install(TARGETS akonadi_tomboynotes_resource ${KDE_INSTALL_TARGETS_DEFAULT_ARGS}) + +install(FILES tomboynotesresource.desktop + DESTINATION "${KDE_INSTALL_DATAROOTDIR}/share/akonadi/agents" +) + +########### summary ############ + +feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/resources/tomboynotes/LICENSE b/resources/tomboynotes/LICENSE new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/resources/tomboynotes/README b/resources/tomboynotes/README new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/README @@ -0,0 +1,14 @@ +==== What's this ? ==== +This is an Akonadi resource for Tomboy-compatible note servers like Grauphel. + +==== Usage ==== +For this resource you need only the URL of your service, +e.g. https://fqdn/index.php/apps/grauphel +It is the same URL that you have used in Tomboy. +For the registration process it will open a web page where you can log in +with your username and password of your account of the note server. + +==== Tested with ==== +Today it's tested only with Grauphel. So it may be incompatible with +other server implemantations (e.g. Rainy). But you are free to test it +and to report your experiences. diff --git a/resources/tomboynotes/acknowledgements.md b/resources/tomboynotes/acknowledgements.md new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/acknowledgements.md @@ -0,0 +1,36 @@ +# o2 by Akos Polster + +OAuth 1.0 and 2.0 for Qt + +> Copyright (c) 2012, Akos Polster +> All rights reserved. + +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions are met: + +> * Redistributions of source code must retain the above copyright notice, this +> list of conditions and the following disclaimer. + +> * Redistributions in binary form must reproduce the above copyright notice, +> this list of conditions and the following disclaimer in the documentation +> and/or other materials provided with the distribution. + +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +> AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +> IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +> DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +> FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +> DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +> SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +# Daniel Vrátil +Unofficial supervisor of this project + +# Other developers of kdepim +The source code of the existing resources and KJots helped me also a lot +to understand what I had to do for the implementation. I have reused some +little parts of the source codes. diff --git a/resources/tomboynotes/configdialog.h b/resources/tomboynotes/configdialog.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/configdialog.h @@ -0,0 +1,31 @@ +#ifndef CONFIGDIALOG_H +#define CONFIGDIALOG_H + +#include + +class KConfigDialogManager; + +class Settings; + +namespace Ui { +class ConfigDialog; +} + +class ConfigDialog : public QDialog +{ + Q_OBJECT + +public: + explicit ConfigDialog(Settings* settings, QWidget *parent=Q_NULLPTR); + ~ConfigDialog(); + + void saveSettings(); + +private: + Ui::ConfigDialog *ui; + + KConfigDialogManager *mManager; + Settings *mSettings; +}; + +#endif // CONFIGDIALOG_H diff --git a/resources/tomboynotes/configdialog.cpp b/resources/tomboynotes/configdialog.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/configdialog.cpp @@ -0,0 +1,60 @@ +#include +#include "configdialog.h" +#include "settings.h" +#include "ui_configdialog.h" + +ConfigDialog::ConfigDialog(Settings* settings, QWidget *parent) : + QDialog(parent), + ui(new Ui::ConfigDialog) +{ + // Create window + setWindowTitle(i18n("Select a tomboy server")); + QWidget *mainWidget = new QWidget(this); + QVBoxLayout *mainLayout = new QVBoxLayout; + setLayout(mainLayout); + mainLayout->addWidget(mainWidget); + ui->setupUi(mainWidget); + + // KSettings stuff + mSettings = settings; + mManager = new KConfigDialogManager(this, settings); + mManager->updateWidgets(); + + // Set the button actions + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &ConfigDialog::accept); + connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &ConfigDialog::reject); + + // Load config dialog window size settings + KConfigGroup group(KSharedConfig::openConfig(), "ConfigDialog"); + const QSize size = group.readEntry("Size", QSize(600, 400)); + if (size.isValid()) { + resize(size); + } + + ui->kcfg_ServerURL->setReadOnly(!mSettings->requestToken().isEmpty()); +} + +ConfigDialog::~ConfigDialog() +{ + // Save config dialog window size + KConfigGroup group(KSharedConfig::openConfig(), "ConfigDialog"); + group.writeEntry("Size", size()); + group.sync(); + + delete ui; +} + +void ConfigDialog::saveSettings() +{ + if ( ui->kcfg_ServerURL->text() != mSettings->serverURL() ) { + mSettings->setRequestToken(""); + mSettings->setRequestTokenSecret(""); + } + + if(ui->kcfg_collectionName->text() == "") { + ui->kcfg_collectionName->setText("Tomboy Notes " + Settings::serverURL()); + } + + mManager->updateSettings(); + mSettings->save(); +} diff --git a/resources/tomboynotes/configdialog.ui b/resources/tomboynotes/configdialog.ui new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/configdialog.ui @@ -0,0 +1,123 @@ + + + Till Adam <adam@kde.org> + ConfigDialog + + + + 0 + 0 + 400 + 290 + + + + Tomboy Server Settings + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + + Tomboy + + + + + + Display name: + + + + + + + + + + Type in the server URL: + + + + + + + This value is not changeable after first setup + + + + + + + Open in read-only mode + + + + + + + Ignore SSL errors + + + + + + + Qt::Vertical + + + + 20 + 141 + + + + + + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + + + + true + + + + + + + + KLineEdit + QLineEdit +
klineedit.h
+
+
+ + +
diff --git a/resources/tomboynotes/o1tomboy.h b/resources/tomboynotes/o1tomboy.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/o1tomboy.h @@ -0,0 +1,37 @@ +#ifndef O1TOMBOY_H +#define O1TOMBOY_H + +#include "o1.h" + +class O1Tomboy : public O1 { + Q_OBJECT +public: + explicit O1Tomboy(QObject *parent = 0) : O1(parent) { + + } + + void setBaseURL(const QString &value) { + setRequestTokenUrl(QUrl(value + "/oauth/request_token")); + setAuthorizeUrl(QUrl(value + "/oauth/authorize")); + setAccessTokenUrl(QUrl(value + "/oauth/access_token")); + setClientId("anyone"); + setClientSecret("anyone"); + } + + QString getRequestToken() { + return requestToken_; + } + + QString getRequestTokenSecret() { + return requestTokenSecret_; + } + + void restoreAuthData(const QString &token, const QString &secret) { + requestToken_ = token; + requestTokenSecret_ = secret; + setLinked(true); + } + +}; + +#endif // O1TOMBOY_H diff --git a/resources/tomboynotes/settings.kcfgc b/resources/tomboynotes/settings.kcfgc new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/settings.kcfgc @@ -0,0 +1,8 @@ +File=tomboynotesresource.kcfg +ClassName=Settings +Mutators=true +ItemAccessors=true +SetUserTexts=true +Singleton=true +#IncludeFiles= +GlobalEnums=true diff --git a/resources/tomboynotes/tomboycollectionsdownloadjob.h b/resources/tomboynotes/tomboycollectionsdownloadjob.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboycollectionsdownloadjob.h @@ -0,0 +1,28 @@ +#ifndef TOMBOYCOLLECTIONSDOWNLOADJOB_H +#define TOMBOYCOLLECTIONSDOWNLOADJOB_H + +#include +#include "tomboyjobbase.h" + +class TomboyCollectionsDownloadJob : public TomboyJobBase +{ + Q_OBJECT +public: + // ctor + explicit TomboyCollectionsDownloadJob(const QString &collectionName, KIO::AccessManager *manager, QObject *parent = 0); + // returns the parsed results wrapped in Akonadi::Collection::List, see bellow + Akonadi::Collection::List collections(); + + // automatically called by KJob + void start() Q_DECL_OVERRIDE; + +private Q_SLOTS: + // This will be called once the request is finished. + void onRequestFinished(); + +private: + Akonadi::Collection::List mResultCollections; + QString mCollectionName; +}; + +#endif // TOMBOYCOLLECTIONSDOWNLOADJOB_H diff --git a/resources/tomboynotes/tomboycollectionsdownloadjob.cpp b/resources/tomboynotes/tomboycollectionsdownloadjob.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboycollectionsdownloadjob.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include "debug.h" +#include "tomboycollectionsdownloadjob.h" + +TomboyCollectionsDownloadJob::TomboyCollectionsDownloadJob(const QString &collectionName, KIO::AccessManager *manager, QObject *parent) + : TomboyJobBase(manager, parent) +{ + mCollectionName = collectionName; +} + +Akonadi::Collection::List TomboyCollectionsDownloadJob::collections() +{ + return mResultCollections; +} + +void TomboyCollectionsDownloadJob::start() +{ + // Get user informations + QNetworkRequest request(mContentURL); + mReply = mRequestor->get(request, QList()); + + connect(mReply, &QNetworkReply::finished, this, &TomboyCollectionsDownloadJob::onRequestFinished); + qCDebug(log_tomboynotesresource) << "TomboyCollectionsDownloadJob: Start network request"; +} + +void TomboyCollectionsDownloadJob::onRequestFinished() +{ + qCDebug(log_tomboynotesresource) << "TomboyCollectionsDownloadJob: Network request finished"; + checkReplyError(); + if (error() != TomboyJobError::NoError) + { + setErrorText(mReply->errorString()); + emitResult(); + return; + } + + // Parse received data as JSON + QJsonDocument document = QJsonDocument::fromJson(mReply->readAll(), Q_NULLPTR); + + QJsonObject jo = document.object(); + qCDebug(log_tomboynotesresource) << "TomboyCollectionsDownloadJob: " << jo; + QJsonValue collectionRevision = jo["latest-sync-revision"]; + qCDebug(log_tomboynotesresource) << "TomboyCollectionsDownloadJob: " << collectionRevision; + + Akonadi::Collection c; + c.setParentCollection( Akonadi::Collection::root()); + c.setRemoteId( mContentURL ); + c.setName( mCollectionName ); + c.setRemoteRevision(QString::number(collectionRevision.toInt())); + qCDebug(log_tomboynotesresource) << "TomboyCollectionsDownloadJob: Sync revision " << collectionRevision.toString(); + + QStringList mimeTypes; + mimeTypes << QLatin1String("text/x-vnd.akonadi.note"); + c.setContentMimeTypes( mimeTypes ); + + mResultCollections << c; + + emitResult(); +} diff --git a/resources/tomboynotes/tomboyitemdownloadjob.h b/resources/tomboynotes/tomboyitemdownloadjob.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyitemdownloadjob.h @@ -0,0 +1,26 @@ +#ifndef TOMBOYITEMDOWNLOADJOB_H +#define TOMBOYITEMDOWNLOADJOB_H + +#include +#include "tomboyjobbase.h" + +class TomboyItemDownloadJob : public TomboyJobBase +{ + Q_OBJECT +public: + TomboyItemDownloadJob(const Akonadi::Item &item, KIO::AccessManager *manager, QObject *parent = 0); + // returns the parsed results wrapped in Akonadi::Item, see bellow + Akonadi::Item item() const; + + // automatically called by KJob + void start() Q_DECL_OVERRIDE; + +private Q_SLOTS: + // This will be called once the request is finished. + void onRequestFinished(); + +private: + Akonadi::Item mResultItem; +}; + +#endif // TOMBOYITEMDOWNLOADJOB_H diff --git a/resources/tomboynotes/tomboyitemdownloadjob.cpp b/resources/tomboynotes/tomboyitemdownloadjob.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyitemdownloadjob.cpp @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include "debug.h" +#include "tomboyitemdownloadjob.h" + +TomboyItemDownloadJob::TomboyItemDownloadJob(const Akonadi::Item &item, KIO::AccessManager *manager, QObject *parent) + : TomboyJobBase(manager, parent) +{ + mResultItem = Akonadi::Item(item); +} + +Akonadi::Item TomboyItemDownloadJob::item() const +{ + return mResultItem; +} + +void TomboyItemDownloadJob::start() +{ + // Get the speicific note + mContentURL.chop(1); + QNetworkRequest request(mContentURL + "/" + mResultItem.remoteId()); + mReply = mRequestor->get(request, QList()); + + connect(mReply, &QNetworkReply::finished, this, &TomboyItemDownloadJob::onRequestFinished); + qCDebug(log_tomboynotesresource) << "TomboyItemDownloadJob: Start network request"; +} + +void TomboyItemDownloadJob::onRequestFinished() +{ + checkReplyError(); + if (error() != TomboyJobError::NoError) + { + setErrorText(mReply->errorString()); + emitResult(); + return; + } + qCDebug(log_tomboynotesresource) << "TomboyItemDownloadJob: Network request finished. No error occured"; + + // Parse received data as JSON + QJsonDocument document = QJsonDocument::fromJson(mReply->readAll(), Q_NULLPTR); + + QJsonObject jsonNote = document.object(); + + qCDebug(log_tomboynotesresource) << "TomboyItemDownloadJob: JSON note: " << jsonNote; + + mResultItem.setRemoteRevision(QString::number(jsonNote["last-sync-revision"].toInt())); + qCDebug(log_tomboynotesresource) << "TomboyItemDownloadJob: Sync revision " << mResultItem.remoteRevision(); + + + // Set timestamp + QString timeStampJson = jsonNote["last-change-date"].toString(); + QDateTime modificationTime = QDateTime::fromString(timeStampJson, Qt::ISODate); + mResultItem.setModificationTime(modificationTime); + + // Set note title + KMime::Message::Ptr akonadiNote = KMime::Message::Ptr(new KMime::Message); + akonadiNote->subject(true)->fromUnicodeString( jsonNote["title"].toString().toUtf8(), "utf-8" ); + + // Set note content + akonadiNote->contentType()->setMimeType("text/enriched"); + akonadiNote->contentType()->setCharset("utf-8"); + akonadiNote->contentTransferEncoding(true)->setEncoding(KMime::Headers::CEquPr); + akonadiNote->mainBodyPart()->fromUnicodeString(jsonNote["note-content"].toString().toUtf8()); + + // Add title and content to Akonadi::Item + akonadiNote->assemble(); + mResultItem.setPayload(akonadiNote); + + emitResult(); +} diff --git a/resources/tomboynotes/tomboyitemsdownloadjob.h b/resources/tomboynotes/tomboyitemsdownloadjob.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyitemsdownloadjob.h @@ -0,0 +1,28 @@ +#ifndef TOMBOYITEMSDOWNLOADJOB_H +#define TOMBOYITEMSDOWNLOADJOB_H + +#include +#include "tomboyjobbase.h" + +class TomboyItemsDownloadJob : public TomboyJobBase +{ + Q_OBJECT +public: + // ctor + TomboyItemsDownloadJob(const Akonadi::Collection::Id &id, KIO::AccessManager *manager, QObject *parent = 0); + // returns the parsed results wrapped in Akonadi::Item::List, see bellow + Akonadi::Item::List items() const; + + // automatically called by KJob + void start() Q_DECL_OVERRIDE; + +private Q_SLOTS: + // This will be called once the request is finished. + void onRequestFinished(); + +private: + Akonadi::Collection::Id mCollectionId; + Akonadi::Item::List mResultItems; +}; + +#endif // TOMBOYITEMSDOWNLOADJOB_H diff --git a/resources/tomboynotes/tomboyitemsdownloadjob.cpp b/resources/tomboynotes/tomboyitemsdownloadjob.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyitemsdownloadjob.cpp @@ -0,0 +1,55 @@ +#include +#include +#include +#include "debug.h" +#include "tomboyitemsdownloadjob.h" + + +TomboyItemsDownloadJob::TomboyItemsDownloadJob(const Akonadi::Collection::Id &id, KIO::AccessManager *manager, QObject *parent) + : TomboyJobBase(manager, parent) +{ + mCollectionId = id; +} + +Akonadi::Item::List TomboyItemsDownloadJob::items() const +{ + return mResultItems; +} + +void TomboyItemsDownloadJob::start() +{ + // Get all notes + QNetworkRequest request(mContentURL); + mReply = mRequestor->get(request, QList()); + + connect(mReply, &QNetworkReply::finished, this, &TomboyItemsDownloadJob::onRequestFinished); + qCDebug(log_tomboynotesresource) << "TomboyItemsDownloadJob: Start network request"; +} + +void TomboyItemsDownloadJob::onRequestFinished() +{ + qCDebug(log_tomboynotesresource) << "TomboyItemsDownloadJob: Network request finished"; + checkReplyError(); + if (error() != TomboyJobError::NoError) + { + setErrorText(mReply->errorString()); + emitResult(); + return; + } + + // Parse received data as JSON + QJsonDocument document = QJsonDocument::fromJson(mReply->readAll(), Q_NULLPTR); + + QJsonObject jo = document.object(); + QJsonArray notes = jo["notes"].toArray(); + + foreach (auto note, notes) { + Akonadi::Item item( "text/x-vnd.akonadi.note" ); + item.setRemoteId(note.toObject()["guid"].toString()); + mResultItems << item; + qCDebug(log_tomboynotesresource) << "TomboyItemsDownloadJob: Retriving note with id" << item.remoteId(); + } + + setError(TomboyJobError::NoError); + emitResult(); +} diff --git a/resources/tomboynotes/tomboyitemuploadjob.h b/resources/tomboynotes/tomboyitemuploadjob.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyitemuploadjob.h @@ -0,0 +1,45 @@ +#ifndef TOMBOYITEMUPLOADJOB_H +#define TOMBOYITEMUPLOADJOB_H + +#include +#include +#include "tomboyjobbase.h" + +enum class JobType +{ + addItem, + modifyItem, + deleteItem +}; + +class TomboyItemUploadJob : public TomboyJobBase +{ + Q_OBJECT +public: + TomboyItemUploadJob(const Akonadi::Item &item, JobType jobType, KIO::AccessManager *manager, QObject *parent = 0); + + // Returns mSourceItem for post-processing purposes + Akonadi::Item item() const; + + JobType jobType(); + + // automatically called by KJob + void start() Q_DECL_OVERRIDE; + +private Q_SLOTS: + // This will be called once the request is finished. + void onRequestFinished(); + +private: + // Workaround for https://bugreports.qt-project.org/browse/QTBUG-26161 Qt bug + QString getCurrentISOTime(); + + Akonadi::Item mSourceItem; + KMime::Message::Ptr mNoteContent; + + JobType mJobType; + + int mRemoteRevision; +}; + +#endif // TOMBOYITEMUPLOADJOB_H diff --git a/resources/tomboynotes/tomboyitemuploadjob.cpp b/resources/tomboynotes/tomboyitemuploadjob.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyitemuploadjob.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include "debug.h" +#include "tomboyitemuploadjob.h" + +TomboyItemUploadJob::TomboyItemUploadJob(const Akonadi::Item &item, JobType jobType, KIO::AccessManager *manager, QObject *parent) + : TomboyJobBase(manager, parent) +{ + mSourceItem = Akonadi::Item(item); + if (item.hasPayload()) { + mNoteContent = item.payload(); + } + + mJobType = jobType; + + mRemoteRevision = item.parentCollection().remoteRevision().toInt(); + + // Create random remote id if adding new item + if (jobType == JobType::addItem) { + mSourceItem.setRemoteId(KRandom::randomString(37)); + } +} + +Akonadi::Item TomboyItemUploadJob::item() const +{ + return mSourceItem; +} + +JobType TomboyItemUploadJob::jobType() +{ + return mJobType; +} + +void TomboyItemUploadJob::start() +{ + // Convert note to JSON + QJsonObject jsonNote; + jsonNote["guid"] = mSourceItem.remoteId(); + switch (mJobType) { + case JobType::deleteItem: + jsonNote["command"] = "delete"; + break; + case JobType::addItem: + jsonNote["create-date"] = getCurrentISOTime(); + case JobType::modifyItem: + jsonNote["title"] = mNoteContent->headerByType("subject")->asUnicodeString(); + jsonNote["note-content"] = mNoteContent->mainBodyPart()->decodedText(); + jsonNote["note-content-version"] = "1"; + jsonNote["last-change-date"] = getCurrentISOTime(); + } + + // Create the full JSON object + QJsonArray noteChanges; + noteChanges.append(jsonNote); + QJsonObject postJson; + postJson["note-changes"] = noteChanges; + postJson["latest-sync-revision"] = QString::number(++mRemoteRevision); + QJsonDocument postData; + postData.setObject(postJson); + + // Network request + QNetworkRequest request(mContentURL); + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json; boundary=7d44e178b0439"); + request.setHeader(QNetworkRequest::ContentLengthHeader, postData.toJson().length()); + mReply = mRequestor->put(request, QList(), postData.toJson()); + connect(mReply, &QNetworkReply::finished, this, &TomboyItemUploadJob::onRequestFinished); + qCDebug(log_tomboynotesresource) << "TomboyItemUploadJob: Start network request"; +} + +void TomboyItemUploadJob::onRequestFinished() +{ + checkReplyError(); + if (error() != TomboyJobError::NoError) + { + setErrorText(mReply->errorString()); + emitResult(); + return; + } + qCDebug(log_tomboynotesresource) << "TomboyItemUploadJob: Network request finished. No error occured"; + + // Parse received data as JSON + QJsonDocument document = QJsonDocument::fromJson(mReply->readAll(), Q_NULLPTR); + + QJsonObject jo = document.object(); + QJsonArray notes = jo["notes"].toArray(); + + // Check if server status is as expected + bool found = false; + foreach (auto note, notes) { + found = (note.toObject()["guid"].toString() == mSourceItem.remoteId()); + if (found) { + break; + } + } + if (mJobType == JobType::deleteItem && found) { + setError(TomboyJobError::PermanentError); + setErrorText("Sync error. Server status not as expected!"); + emitResult(); + return; + } + if (mJobType != JobType::deleteItem && !found) { + setError(TomboyJobError::PermanentError); + setErrorText("Sync error. Server status not as expected!"); + emitResult(); + return; + } + + setError(TomboyJobError::NoError); + emitResult(); +} + +QString TomboyItemUploadJob::getCurrentISOTime() +{ + QDateTime local = QDateTime::currentDateTime(); + QDateTime utc = local.toUTC(); + utc.setTimeSpec(Qt::LocalTime); + int utcOffset = utc.secsTo(local); + local.setUtcOffset(utcOffset); + + return local.toString(Qt::ISODate); +} diff --git a/resources/tomboynotes/tomboyjobbase.h b/resources/tomboynotes/tomboyjobbase.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyjobbase.h @@ -0,0 +1,38 @@ +#ifndef TOMBOYJOBBASE_H +#define TOMBOYJOBBASE_H + +#include +#include +#include +#include "o1tomboy.h" +#include "o1requestor.h" + +enum TomboyJobError +{ + NoError, + TemporaryError, + PermanentError +}; + +class TomboyJobBase : public KCompositeJob +{ + Q_OBJECT +public: + explicit TomboyJobBase(KIO::AccessManager *manager, QObject *parent = Q_NULLPTR); + + void setServerURL(const QString &apiurl, const QString &contenturl); + void setAuthentication(const QString &token, const QString &secret); + +protected: + KIO::Integration::AccessManager *mManager; + O1Requestor *mRequestor; + O1Tomboy *mO1; + QNetworkReply *mReply; + + QString mApiURL; + QString mContentURL; + + TomboyJobError checkReplyError(); +}; + +#endif // TOMBOYJOBBASE_H diff --git a/resources/tomboynotes/tomboyjobbase.cpp b/resources/tomboynotes/tomboyjobbase.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyjobbase.cpp @@ -0,0 +1,37 @@ +#include "tomboyjobbase.h" + + +TomboyJobBase::TomboyJobBase(KIO::AccessManager *manager, QObject *parent) + : KCompositeJob(parent) +{ + // Create the OAuth objects + mO1 = new O1Tomboy(this); + mManager = manager; + mRequestor = new O1Requestor(mManager, mO1, this); +} + +void TomboyJobBase::setServerURL(const QString &apiurl, const QString &contenturl) +{ + mO1->setBaseURL(apiurl); + mApiURL = apiurl + "/api/1.0"; + mContentURL = contenturl; +} + +void TomboyJobBase::setAuthentication(const QString &token, const QString &secret) +{ + mO1->restoreAuthData(token, secret); +} + +TomboyJobError TomboyJobBase::checkReplyError() +{ + switch (mReply->error()) { + case QNetworkReply::NoError : + return TomboyJobError::NoError; + case QNetworkReply::RemoteHostClosedError: + case QNetworkReply::HostNotFoundError: + case QNetworkReply::TimeoutError: + return TomboyJobError::TemporaryError; + default: + return TomboyJobError::PermanentError; + } +} diff --git a/resources/tomboynotes/tomboynotesresource.h b/resources/tomboynotes/tomboynotesresource.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboynotesresource.h @@ -0,0 +1,63 @@ +#ifndef TOMBOYNOTESRESOURCE_H +#define TOMBOYNOTESRESOURCE_H + + +#include +#include +#include +#include "o1tomboy.h" +#include "o1requestor.h" + +class TomboyNotesResource : public Akonadi::ResourceBase, + public Akonadi::AgentBase::Observer +{ + Q_OBJECT + +public: + TomboyNotesResource(const QString &id); + ~TomboyNotesResource(); + +public Q_SLOTS: + void configure(WId windowId) Q_DECL_OVERRIDE; + +protected Q_SLOTS: + // Standard akonadi slots + void retrieveCollections() Q_DECL_OVERRIDE; + void retrieveItems(const Akonadi::Collection &col) Q_DECL_OVERRIDE; + bool retrieveItem(const Akonadi::Item &item, const QSet &parts) Q_DECL_OVERRIDE; + + // Slots for Job result handling + void onAuthorizationFinished(KJob *kjob); + void onCollectionsRetrieved(KJob *kjob); + void onItemChangeCommitted(KJob *kjob); + void onItemRetrieved(KJob *kjob); + void onItemsRetrieved(KJob *kjob); + +private Q_SLOTS: + // Status handling + void clearStatusMessage(); + void onSslError(QNetworkReply *reply, const QList &errors); + +protected: + void aboutToQuit() Q_DECL_OVERRIDE; + + // Standard akonadi + void itemAdded(const Akonadi::Item &item, const Akonadi::Collection &collection) Q_DECL_OVERRIDE; + void itemChanged(const Akonadi::Item &item, const QSet &parts) Q_DECL_OVERRIDE; + void itemRemoved(const Akonadi::Item &item) Q_DECL_OVERRIDE; + +private: + bool configurationNotValid(); + + void retryAfterFailure(const QString &errorMessage); + // Status handling + void showError(const QString errorText); + QTimer *mStatusMessageTimer; + + // Only one UploadJob should run per time + bool mUploadJobProcessRunning; + + KIO::AccessManager *mManager; +}; + +#endif diff --git a/resources/tomboynotes/tomboynotesresource.cpp b/resources/tomboynotes/tomboynotesresource.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboynotesresource.cpp @@ -0,0 +1,311 @@ +#include +#include +#include +#include +#include +#include +#include "debug.h" +#include "configdialog.h" +#include "settings.h" +#include "settingsadaptor.h" +#include "tomboyserverauthenticatejob.h" +#include "tomboycollectionsdownloadjob.h" +#include "tomboyitemdownloadjob.h" +#include "tomboyitemsdownloadjob.h" +#include "tomboyitemuploadjob.h" +#include "tomboynotesresource.h" + +using namespace Akonadi; + +TomboyNotesResource::TomboyNotesResource(const QString &id) + : ResourceBase(id) +{ + new SettingsAdaptor(Settings::self()); + QDBusConnection::sessionBus().registerObject(QStringLiteral("/Settings"), + Settings::self(), + QDBusConnection::ExportAdaptors); + + // Akonadi:Item should always provide the payload + changeRecorder()->itemFetchScope().fetchFullPayload(true); + + // Status message stuff + mStatusMessageTimer = new QTimer(this); + mStatusMessageTimer->setSingleShot(true); + connect(mStatusMessageTimer, &QTimer::timeout, this, &TomboyNotesResource::clearStatusMessage); + connect(this, &AgentBase::error, this, &TomboyNotesResource::showError); + + mUploadJobProcessRunning = false; + + mManager = new KIO::AccessManager(this); + connect(mManager, &KIO::AccessManager::sslErrors, this, &TomboyNotesResource::onSslError); + + qCDebug(log_tomboynotesresource) << "Resource started"; +} + +TomboyNotesResource::~TomboyNotesResource() +{ + delete mStatusMessageTimer; +} + +void TomboyNotesResource::retrieveCollections() +{ + qCDebug(log_tomboynotesresource) << "Retriving collections started"; + + auto job = new TomboyCollectionsDownloadJob(Settings::collectionName(), mManager, this); + job->setAuthentication(Settings::requestToken(), Settings::requestTokenSecret()); + job->setServerURL(Settings::serverURL(), Settings::userURL()); + // connect to its result() signal + connect(job, &KJob::result, this, &TomboyNotesResource::onCollectionsRetrieved); + job->start(); + qCDebug(log_tomboynotesresource) << "Retriving collections job started"; +} + + +void TomboyNotesResource::retrieveItems(const Akonadi::Collection &collection) +{ + if (configurationNotValid()) { + cancelTask("Resource configuration is not valid"); + return; + } + + // create the job + auto job = new TomboyItemsDownloadJob(collection.id(), mManager, this); + job->setAuthentication(Settings::requestToken(), Settings::requestTokenSecret()); + job->setServerURL(Settings::serverURL(), Settings::contentURL()); + // connect to its result() signal + connect(job, &KJob::result, this, &TomboyNotesResource::onItemsRetrieved); + job->start(); + qCDebug(log_tomboynotesresource) << "Retriving items job started"; +} + +bool TomboyNotesResource::retrieveItem(const Akonadi::Item &item, const QSet &parts) +{ + Q_UNUSED( parts ); + + if (configurationNotValid()) { + cancelTask("Resource configuration is not valid"); + return false; + } + + // this method is called when Akonadi wants more data for a given item. + auto job = new TomboyItemDownloadJob(item, mManager, this); + job->setAuthentication(Settings::requestToken(), Settings::requestTokenSecret()); + job->setServerURL(Settings::serverURL(), Settings::contentURL()); + // connect to its result() signal + connect(job, &KJob::result, this, &TomboyNotesResource::onItemRetrieved); + job->start(); + qCDebug(log_tomboynotesresource) << "Retriving item data job started"; + + return true; +} + +void TomboyNotesResource::onAuthorizationFinished(KJob *kjob) +{ + // Saves the received client authentication data in the settings + qCDebug(log_tomboynotesresource) << "Authorization job finished"; + auto job = qobject_cast(kjob); + if (job->error() == TomboyJobError::NoError) { + Settings::setRequestToken(job->getRequestToken()); + Settings::setRequestTokenSecret(job->getRequestTokenSecret()); + Settings::setContentURL(job->getContentUrl()); + Settings::setUserURL(job->getUserURL()); + Settings::self()->save(); + synchronizeCollectionTree(); + synchronize(); + } + else { + showError(job->errorText()); + } +} + +void TomboyNotesResource::onCollectionsRetrieved(KJob *kjob) +{ + auto job = qobject_cast(kjob); + if (job->error() != TomboyJobError::NoError) { + cancelTask(); + showError(job->errorText()); + return; + } + + collectionsRetrieved(job->collections()); +} + +void TomboyNotesResource::onItemChangeCommitted(KJob *kjob) +{ + auto job = qobject_cast(kjob); + mUploadJobProcessRunning = false; + switch (job->error()) { + case TomboyJobError::PermanentError: + cancelTask(); + showError(job->errorText()); + return; + case TomboyJobError::TemporaryError: + retryAfterFailure(job->errorString()); + return; + case TomboyJobError::NoError: + changeCommitted(job->item()); + // The data should be actualized for the next UploadJob + synchronize(); + return; + } +} + +void TomboyNotesResource::onItemRetrieved(KJob *kjob) +{ + auto job = qobject_cast(kjob); + + if (job->error() != TomboyJobError::NoError) { + cancelTask(); + showError(job->errorText()); + return; + } + + itemRetrieved(job->item()); + qCDebug(log_tomboynotesresource) << "Retriving item data job with remoteId " << job->item().remoteId() << " finished"; +} + +void TomboyNotesResource::onItemsRetrieved(KJob *kjob) +{ + auto job = qobject_cast(kjob); + if (job->error() != TomboyJobError::NoError) { + cancelTask(); + showError(job->errorText()); + return; + } + + itemsRetrieved(job->items()); + qCDebug(log_tomboynotesresource) << "Retriving items job finished"; +} + +void TomboyNotesResource::clearStatusMessage() +{ + Q_EMIT status(Akonadi::AgentBase::Idle, QString()); +} + +void TomboyNotesResource::onSslError(QNetworkReply *reply, const QList &errors) +{ + if (Settings::ignoreSslErrors()) { + reply->ignoreSslErrors(); + } +} + +void TomboyNotesResource::aboutToQuit() +{ + // TODO: any cleanup you need to do while there is still an active + // event loop. The resource will terminate after this method returns +} + +void TomboyNotesResource::configure(WId windowId) +{ + qCDebug(log_tomboynotesresource) << "Resource configuration started"; + + ConfigDialog dialog(Settings::self()); + + if (windowId) { + KWindowSystem::setMainWindow(&dialog, windowId); + } + + // Run the configuration dialog an sve settings if accepted + if (dialog.exec() != QDialog::Accepted) { + return; + } + + dialog.saveSettings(); + setAgentName(Settings::collectionName()); + + if (configurationNotValid()) + { + auto job = new TomboyServerAuthenticateJob(mManager, this); + job->setServerURL(Settings::serverURL(), ""); + connect(job, &KJob::result, this, &TomboyNotesResource::onAuthorizationFinished); + job->start(); + qCDebug(log_tomboynotesresource) << "Authorization job started"; + } + else { + synchronize(); + } +} + +void TomboyNotesResource::itemAdded(const Akonadi::Item &item, const Akonadi::Collection &collection) +{ + Q_UNUSED( collection ); + if (Settings::readOnly() || configurationNotValid()) { + cancelTask("Resource is read-only"); + return; + } + + if (mUploadJobProcessRunning) { + retryAfterFailure(""); + return; + } + + auto job = new TomboyItemUploadJob(item, JobType::addItem, mManager, this); + job->setAuthentication(Settings::requestToken(), Settings::requestTokenSecret()); + job->setServerURL(Settings::serverURL(), Settings::contentURL()); + connect(job, &KJob::result, this, &TomboyNotesResource::onItemChangeCommitted); + mUploadJobProcessRunning = true; + job->start(); +} + +void TomboyNotesResource::itemChanged(const Akonadi::Item &item, const QSet &parts) +{ + Q_UNUSED( parts ); + if (Settings::readOnly() || configurationNotValid()) { + cancelTask("Resource is read-only"); + return; + } + + if (mUploadJobProcessRunning) { + retryAfterFailure(""); + return; + } + + auto job = new TomboyItemUploadJob(item, JobType::modifyItem, mManager, this); + job->setAuthentication(Settings::requestToken(), Settings::requestTokenSecret()); + job->setServerURL(Settings::serverURL(), Settings::contentURL()); + connect(job, &KJob::result, this, &TomboyNotesResource::onItemChangeCommitted); + mUploadJobProcessRunning = true; + job->start(); +} + +void TomboyNotesResource::itemRemoved(const Akonadi::Item &item) +{ + if (Settings::readOnly() || configurationNotValid()) { + cancelTask("Resource is read-only"); + return; + } + + if (mUploadJobProcessRunning) { + retryAfterFailure(""); + return; + } + + auto job = new TomboyItemUploadJob(item, JobType::deleteItem, mManager, this); + job->setAuthentication(Settings::requestToken(), Settings::requestTokenSecret()); + job->setServerURL(Settings::serverURL(), Settings::contentURL()); + connect(job, &KJob::result, this, &TomboyNotesResource::onItemChangeCommitted); + mUploadJobProcessRunning = true; + job->start(); +} + +bool TomboyNotesResource::configurationNotValid() +{ + return Settings::requestToken().isEmpty() || Settings::requestToken().isEmpty() || Settings::contentURL().isEmpty(); +} + +void TomboyNotesResource::retryAfterFailure(const QString &errorMessage) +{ + Q_EMIT status(Broken, errorMessage); + deferTask(); + setTemporaryOffline(Settings::self()->refreshInterval() <= 0 ? 300 : Settings::self()->refreshInterval() * 60); +} + +void TomboyNotesResource::showError(const QString errorText) +{ + Q_EMIT status(Akonadi::AgentBase::Idle, errorText); + mStatusMessageTimer->start(1000 * 10); +} + +AKONADI_RESOURCE_MAIN(TomboyNotesResource) + +#include "moc_tomboynotesresource.cpp" diff --git a/resources/tomboynotes/tomboynotesresource.desktop b/resources/tomboynotes/tomboynotesresource.desktop new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboynotesresource.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Name=Akonadi TomboyNotes Resource +Comment=Resource for tomboy compatible notes server +Type=AkonadiResource +Exec=akonadi_tomboynotes_resource +Icon=view-pim-notes + +X-Akonadi-MimeTypes=text/x-vnd.akonadi.note +X-Akonadi-Capabilities=Resource,Notes +X-Akonadi-Identifier=akonadi_tomboynotes_resource diff --git a/resources/tomboynotes/tomboynotesresource.kcfg b/resources/tomboynotes/tomboynotesresource.kcfg new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboynotesresource.kcfg @@ -0,0 +1,50 @@ + + + + + + + + + + + http://localhost/owncloud/index.php/apps/grauphel + + + + + + + + + + + + + + + + + + + + + + + + false + + + + false + + + + 5 + + + diff --git a/resources/tomboynotes/tomboyserverauthenticatejob.h b/resources/tomboynotes/tomboyserverauthenticatejob.h new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyserverauthenticatejob.h @@ -0,0 +1,36 @@ +#ifndef TOMBOYSERVERAUTHENTICATEJOB_H +#define TOMBOYSERVERAUTHENTICATEJOB_H + +#include +#include "tomboyjobbase.h" + + +class TomboyServerAuthenticateJob : public TomboyJobBase +{ + Q_OBJECT +public: + TomboyServerAuthenticateJob(KIO::AccessManager *manager, QObject *parent = Q_NULLPTR); + + QString getRequestToken(); + QString getRequestTokenSecret(); + QString getContentUrl(); + QString getUserURL(); + + void start() Q_DECL_OVERRIDE; + +private Q_SLOTS: + void onLinkingFailed(); + void onLinkingSucceeded(); + void onLinkedChanged(); + void onOpenBrowser(const QUrl &url); + void onCloseBrowser(); + + void onApiRequestFinished(); + void onUserRequestFinished(); + +private: + QString mUserURL; + +}; + +#endif // TOMBOYSERVERAUTHENTICATEJOB_H diff --git a/resources/tomboynotes/tomboyserverauthenticatejob.cpp b/resources/tomboynotes/tomboyserverauthenticatejob.cpp new file mode 100644 --- /dev/null +++ b/resources/tomboynotes/tomboyserverauthenticatejob.cpp @@ -0,0 +1,114 @@ +#include +#include +#include +#include +#include "debug.h" +#include "tomboyserverauthenticatejob.h" + +TomboyServerAuthenticateJob::TomboyServerAuthenticateJob(KIO::AccessManager *manager, QObject *parent) + : TomboyJobBase(manager, parent) +{ + // Connect the o2 authenfication signals + connect(mO1, SIGNAL(linkedChanged()), this, SLOT(onLinkedChanged())); + connect(mO1, SIGNAL(linkingFailed()), this, SLOT(onLinkingFailed())); + connect(mO1, SIGNAL(linkingSucceeded()), this, SLOT(onLinkingSucceeded())); + connect(mO1, SIGNAL(openBrowser(QUrl)), this, SLOT(onOpenBrowser(QUrl))); + connect(mO1, SIGNAL(closeBrowser()), this, SLOT(onCloseBrowser())); +} + +void TomboyServerAuthenticateJob::start() +{ + mO1->link(); +} + +QString TomboyServerAuthenticateJob::getRequestToken() +{ + return mO1->getRequestToken(); +} + +QString TomboyServerAuthenticateJob::getRequestTokenSecret() +{ + return mO1->getRequestTokenSecret(); +} + +QString TomboyServerAuthenticateJob::getContentUrl() +{ + return mContentURL; +} + +QString TomboyServerAuthenticateJob::getUserURL() +{ + return mUserURL; +} + +void TomboyServerAuthenticateJob::onLinkingFailed() +{ + setError(TomboyJobError::PermanentError); + setErrorText("Authorization has been failed!"); + emitResult(); +} + +void TomboyServerAuthenticateJob::onLinkingSucceeded() +{ + QNetworkRequest request(mApiURL); + mReply = mRequestor->get(request, QList()); + + connect(mReply, &QNetworkReply::finished, this, &TomboyServerAuthenticateJob::onApiRequestFinished); + qCDebug(log_tomboynotesresource) << "TomboyServerAuthenticateJob: Start network request"; +} + +void TomboyServerAuthenticateJob::onLinkedChanged() +{ + +} + +void TomboyServerAuthenticateJob::onOpenBrowser(const QUrl &url) +{ + QDesktopServices::openUrl(url); +} + +void TomboyServerAuthenticateJob::onCloseBrowser() +{ + +} + +void TomboyServerAuthenticateJob::onApiRequestFinished() +{ + checkReplyError(); + if (error() != TomboyJobError::NoError) + { + setErrorText(mReply->errorString()); + emitResult(); + return; + } + + // Parse received data as JSON and get user-href + QJsonDocument document = QJsonDocument::fromJson(mReply->readAll(), Q_NULLPTR); + QJsonObject jo = document.object(); + mUserURL = jo["user-ref"].toObject()["api-ref"].toString(); + + QNetworkRequest request(mUserURL); + mReply = mRequestor->get(request, QList()); + + connect(mReply, &QNetworkReply::finished, this, &TomboyServerAuthenticateJob::onUserRequestFinished); + qCDebug(log_tomboynotesresource) << "TomboyServerAuthenticateJob: Start network request"; +} + +void TomboyServerAuthenticateJob::onUserRequestFinished() +{ + checkReplyError(); + if (error() != TomboyJobError::NoError) + { + setErrorText(mReply->errorString()); + emitResult(); + return; + } + + // Parse received data as JSON and get contentURL + QJsonDocument document = QJsonDocument::fromJson(mReply->readAll(), Q_NULLPTR); + QJsonObject jo = document.object(); + mContentURL = jo["notes-ref"].toObject()["api-ref"].toString(); + + setError(TomboyJobError::NoError); + emitResult(); +}