From d3fd4039e986ca09e717a329c333842b141609ef Mon Sep 17 00:00:00 2001
From: Armin Felder <armin.felder@osalliance.com>
Date: Mon, 3 Dec 2018 02:24:50 +0100
Subject: [PATCH] fix storage location for attachments

---
 CustomModels/messagemodel.cpp |  24 ++++--
 repos/channelrepository.cpp   |  30 ++++---
 repos/messagerepository.cpp   |   6 +-
 rocketchat.cpp                | 154 ++++++++++++----------------------
 rocketchatserver.cpp          |   2 +-
 services/fileservice.cpp      | 133 +++++++++++++++++++++--------
 services/fileservice.h        |   3 +-
 7 files changed, 198 insertions(+), 154 deletions(-)

diff --git a/CustomModels/messagemodel.cpp b/CustomModels/messagemodel.cpp
index eb34ca4..d1645e9 100644
--- a/CustomModels/messagemodel.cpp
+++ b/CustomModels/messagemodel.cpp
@@ -101,13 +101,20 @@ QVariant MessagesModel::data( const QModelIndex &index, int role ) const
         case MessageRoles::id:
             return messageAtIndex->getId();
 
-        case   MessageRoles::replyMessage: {
+        case MessageRoles::replyMessage: {
                 auto attachments = messageAtIndex->getAttachments();
 
                 if ( !attachments.isEmpty() ) {
                     auto first = attachments.first();
-                    auto msg =  qSharedPointerCast<RocketChatReplyMessage>( first );
-                    return msg->getMessageString();
+
+                    if ( !first.isNull() ) {
+                        //TODO: WTF!!!
+                        auto msg =  qSharedPointerCast<RocketChatReplyMessage>( first );
+
+                        if ( !msg.isNull() ) {
+                            return msg->getMessageString();
+                        }
+                    }
                 }
             }
             break;
@@ -117,8 +124,15 @@ QVariant MessagesModel::data( const QModelIndex &index, int role ) const
 
                 if ( !attachments.isEmpty() ) {
                     auto first = attachments.first();
-                    auto msg =  qSharedPointerCast<RocketChatReplyMessage>( first );
-                    return msg->getAuthor();
+
+                    if ( !first.isNull() ) {
+                        //TODO: WTF!!!
+                        auto msg =  qSharedPointerCast<RocketChatReplyMessage>( first );
+
+                        if ( !msg.isNull() ) {
+                            return msg->getAuthor();
+                        }
+                    }
                 }
             }
             break;
diff --git a/repos/channelrepository.cpp b/repos/channelrepository.cpp
index 1e09807..9b03930 100755
--- a/repos/channelrepository.cpp
+++ b/repos/channelrepository.cpp
@@ -32,21 +32,25 @@ bool ChannelRepository::add( const QString &id, const QSharedPointer<RocketChatC
     connect( msg.data(), &RocketChatChannel::messageAdded, this, &ChannelRepository::receiveTimestamp, Qt::UniqueConnection );
     QString type = msg->getType();
 
-    if ( type == "c" ) {
-        auto result = QMetaObject::invokeMethod( mChannelsModel,  "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
-        Q_ASSERT( result );
-    } else if ( type == "d" ) {
-        auto result = QMetaObject::invokeMethod( mDirectModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
-        Q_ASSERT( result );
-    } else if ( type == "p" ) {
-        auto result = QMetaObject::invokeMethod( mGroupsModel,  "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
+    if ( !mElements.contains( id ) ) {
+        if ( type == "c" ) {
+            auto result = QMetaObject::invokeMethod( mChannelsModel,  "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
+            Q_ASSERT( result );
+        } else if ( type == "d" ) {
+            auto result = QMetaObject::invokeMethod( mDirectModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
+            Q_ASSERT( result );
+        } else if ( type == "p" ) {
+            auto result = QMetaObject::invokeMethod( mGroupsModel,  "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
+            Q_ASSERT( result );
+        }
+
+        mNameIndex[msg->getName()] = msg;
+        auto result = QMetaObject::invokeMethod( mMessagesModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
         Q_ASSERT( result );
+        return AbstractBaseRepository::add( id, msg );
+    } else {
+        return false;
     }
-
-    mNameIndex[msg->getName()] = msg;
-    auto result = QMetaObject::invokeMethod( mMessagesModel, "addChannelSlot", Q_ARG( QSharedPointer<RocketChatChannel>, msg ) );
-    Q_ASSERT( result );
-    return AbstractBaseRepository::add( id, msg );
 }
 
 bool ChannelRepository::add( const QSharedPointer<RocketChatChannel> &pChannel )
diff --git a/repos/messagerepository.cpp b/repos/messagerepository.cpp
index cc337b1..f733971 100755
--- a/repos/messagerepository.cpp
+++ b/repos/messagerepository.cpp
@@ -99,8 +99,10 @@ void MessageRepository::setTimestampIndex( const QMap<qint64, QSharedPointer<Roc
 bool MessageRepository::add( const QString &pId, const QSharedPointer<RocketChatMessage> &pMsg )
 {
     if ( !pMsg.isNull() ) {
-        mTimestampIndex[pMsg->getTimestamp()] = pMsg;
-        return AbstractBaseRepository::add( pId, pMsg );
+        if ( !mElements.contains( pId ) ) {
+            mTimestampIndex[pMsg->getTimestamp()] = pMsg;
+            return AbstractBaseRepository::add( pId, pMsg );
+        }
     }
 
     return false;
diff --git a/rocketchat.cpp b/rocketchat.cpp
index b87c507..359ad36 100755
--- a/rocketchat.cpp
+++ b/rocketchat.cpp
@@ -87,7 +87,7 @@ RocketChat::RocketChat( QGuiApplication *app )
 #endif
     qRegisterMetaType<ConnectionState>( "ConnectionState" );
     qRegisterMetaType<Qt::ApplicationState>( "Qt::ApplicationState" );
-    // qInstallMessageHandler( customOutput );
+    qInstallMessageHandler( customOutput );
 }
 
 RocketChat::~RocketChat()
@@ -121,8 +121,7 @@ void RocketChat::joinChannel( const QString &pServerId, const QString &pChannelI
 
     if ( mServerStatus ) {
 
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "joinChannel", Q_ARG( QString, pChannelId ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "joinChannel", Q_ARG( QString, pChannelId ) );
 
         if ( !mFileToShare.isEmpty() ) {
             uploadSharedFileToChannel( pChannelId );
@@ -136,8 +135,7 @@ void RocketChat::joinChannelByNameAndType( const QString &pServerId, const QStri
 
     if ( mServerStatus ) {
 
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "joinChannelByNameAndType", Q_ARG( QString, pChannelName ), Q_ARG( QString, pType ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "joinChannelByNameAndType", Q_ARG( QString, pChannelName ), Q_ARG( QString, pType ) );
     }
 }
 
@@ -146,8 +144,7 @@ void RocketChat::login( const QString &pServerId, const QString &pUsername, cons
     Q_UNUSED( pServerId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "login", Q_ARG( QString, pUsername ), Q_ARG( QString, pPassword ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "login", Q_ARG( QString, pUsername ), Q_ARG( QString, pPassword ) );
     }
 }
 
@@ -155,8 +152,7 @@ void RocketChat::loginWithSamlToken( const QString &pToken )
 {
     if ( !pToken.isEmpty() ) {
         if ( mServerStatus ) {
-            auto result = QMetaObject::invokeMethod( mServerMap.first(),  "loginWtihSamlToken", Q_ARG( QString, pToken ) );
-            Q_ASSERT( result );
+            QMetaObject::invokeMethod( mServerMap.first(),  "loginWtihSamlToken", Q_ARG( QString, pToken ) );
         }
     }
 }
@@ -164,24 +160,21 @@ void RocketChat::loginWithSamlToken( const QString &pToken )
 void RocketChat::loginWithMethod( const QString &method, const QString &payload )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "loginWithMethod", Q_ARG( QString, method ), Q_ARG( QString, payload ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "loginWithMethod", Q_ARG( QString, method ), Q_ARG( QString, payload ) );
     }
 }
 
 void RocketChat::loadRecentHistory( const QString &pChannelId )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "loadRecentHistory", Q_ARG( QString, pChannelId ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "loadRecentHistory", Q_ARG( QString, pChannelId ) );
     }
 }
 
 void RocketChat::loadHistoryTill( const QString &pChannelId, qint64 pTs )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "loadHistoryTill", Q_ARG( QString, pChannelId ), Q_ARG( qint64, pTs ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "loadHistoryTill", Q_ARG( QString, pChannelId ), Q_ARG( qint64, pTs ) );
     }
 }
 
@@ -222,8 +215,7 @@ bool RocketChat::customEmojisReady()
 void RocketChat::checkLoggedIn()
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "requestIsLoggedIn" );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "requestIsLoggedIn" );
     }
 }
 
@@ -232,16 +224,14 @@ void RocketChat::getChannelDetails( const QString &pServerId, const QString &pCh
     Q_UNUSED( pServerId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "requestGetChannelDetails", Q_ARG( QString, pChannelName ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "requestGetChannelDetails", Q_ARG( QString, pChannelName ) );
     }
 }
 
 void RocketChat::createVideoCall( const QString &pServerId, const QString &pChannelId )
 {
     Q_UNUSED( pServerId );
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "createVideoCall", Q_ARG( QString, pChannelId ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "createVideoCall", Q_ARG( QString, pChannelId ) );
 }
 
 void RocketChat::copyToClipboard( const QString &text )
@@ -251,56 +241,47 @@ void RocketChat::copyToClipboard( const QString &text )
 
 void RocketChat::blockUser( const QString &pChannelId )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "blockUser", Q_ARG( QString, pChannelId ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "blockUser", Q_ARG( QString, pChannelId ) );
 }
 
 void RocketChat::unBlockUser( const QString &pChannelId )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "unBlockUser", Q_ARG( QString, pChannelId ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "unBlockUser", Q_ARG( QString, pChannelId ) );
 }
 
 void RocketChat::leaveChannel( const QString &pChannelId )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "leaveChannel", Q_ARG( QString, pChannelId ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "leaveChannel", Q_ARG( QString, pChannelId ) );
 }
 
 void RocketChat::hideChannel( const QString &pChannelId )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "hideChannel", Q_ARG( QString, pChannelId ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "hideChannel", Q_ARG( QString, pChannelId ) );
 }
 
 void RocketChat::reportAbusiveContent( const QString &pMessageId, const QString &pAuthor )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "reportAbusiveContent", Q_ARG( QString, pMessageId ), Q_ARG( QString, pAuthor ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "reportAbusiveContent", Q_ARG( QString, pMessageId ), Q_ARG( QString, pAuthor ) );
 }
 
 void RocketChat::searchMessage( const QString &pTerm, const QString &pChannelId )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "searchMessage", Q_ARG( QString, pTerm ), Q_ARG( QString, pChannelId ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "searchMessage", Q_ARG( QString, pTerm ), Q_ARG( QString, pChannelId ) );
 }
 
 void RocketChat::searchRoom( const QString &pTerm )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "searchRoom", Q_ARG( QString, pTerm ), Q_ARG( QString, "" ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "searchRoom", Q_ARG( QString, pTerm ), Q_ARG( QString, "" ) );
 }
 
 void RocketChat::searchRoomByType( const QString &pTerm, const QString &pType )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "searchRoom", Q_ARG( QString, pTerm ), Q_ARG( QString, pType ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "searchRoom", Q_ARG( QString, pTerm ), Q_ARG( QString, pType ) );
 }
 
 void RocketChat::setUserDefaultStatus( int pStatus )
 {
-    auto result = QMetaObject::invokeMethod( mServerMap.first(), "setUserPresenceDefaultStatus", Q_ARG( int, pStatus ) );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( mServerMap.first(), "setUserPresenceDefaultStatus", Q_ARG( int, pStatus ) );
 }
 
 void RocketChat::clearWebViewCookies()
@@ -333,8 +314,7 @@ bool RocketChat::newServerByDomain( const QString &domain, bool pUnsecure = fals
                 registerServer( server );
                 newServerMutex.unlock();
             } );
-            auto result = QMetaObject::invokeMethod( firstServer, "deleteLater" );
-            Q_ASSERT( result );
+            QMetaObject::invokeMethod( firstServer, "deleteLater" );
         }
 
     } else {
@@ -353,7 +333,7 @@ bool RocketChat::newServerByDomain( const QString &domain, bool pUnsecure = fals
 
     }
 
-    return false;
+    return 0;
 }
 
 void RocketChat::openPrivateChannelWith( const QString &pServerId, const QString &pUsername )
@@ -361,24 +341,21 @@ void RocketChat::openPrivateChannelWith( const QString &pServerId, const QString
     Q_UNUSED( pServerId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "openPrivateChannelWith", Q_ARG( QString, pUsername ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "openPrivateChannelWith", Q_ARG( QString, pUsername ) );
     }
 }
 
 void RocketChat::getFileRessource( const QString &pUrl )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "getFileRessource", Q_ARG( QString, pUrl ), Q_ARG( QString, QStringLiteral( "temp" ) ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "getFileRessource", Q_ARG( QString, pUrl ), Q_ARG( QString, QStringLiteral( "temp" ) ) );
     }
 }
 
 void RocketChat::getFileRessource( const QString &pUrl, const QString &pType )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "getFileRessource", Q_ARG( QString, pUrl ), Q_ARG( QString, pType ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "getFileRessource", Q_ARG( QString, pUrl ), Q_ARG( QString, pType ) );
     }
 }
 
@@ -418,8 +395,7 @@ void RocketChat::addUsersToChannel( const QString &pServerId, const QString &pCh
 
     if ( mServerStatus ) {
         QStringList unserList = pUsernames.split( ',' );
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "addUsersToChannel", Q_ARG( QString, pChannelName ), Q_ARG( QStringList, unserList ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "addUsersToChannel", Q_ARG( QString, pChannelName ), Q_ARG( QStringList, unserList ) );
     }
 }
 
@@ -430,8 +406,7 @@ void RocketChat::sendMessage( const QString &pServerId, const QString &pChannelI
 
     if ( mServerStatus ) {
         RocketChatServerData *server = mServerMap.first();
-        auto result = QMetaObject::invokeMethod( server,  "sendMessage", Q_ARG( QString, pChannelId ), Q_ARG( QString, pMessage ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( server,  "sendMessage", Q_ARG( QString, pChannelId ), Q_ARG( QString, pMessage ) );
     }
 }
 
@@ -482,8 +457,7 @@ QString RocketChat::getCleanString( const QString &pText )
 void RocketChat::uploadSharedFileToChannel( const QString &pChannelId )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "uploadFile", Q_ARG( QString, pChannelId ), Q_ARG( QString, mFileToShare ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "uploadFile", Q_ARG( QString, pChannelId ), Q_ARG( QString, mFileToShare ) );
         mFileToShare.clear();
     }
 }
@@ -494,8 +468,7 @@ void RocketChat::joinJitsiCall( const QString &pServer, const QString &pChannelI
     Q_UNUSED( pMessageId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "joinJitsiCall", Q_ARG( QString, pChannelIdm ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "joinJitsiCall", Q_ARG( QString, pChannelIdm ) );
     }
 }
 
@@ -506,10 +479,9 @@ QString RocketChat::getUsername( const QString &pServerId )
 
     if ( mServerStatus ) {
         return mServerMap.first()->getUsername();
+    } else {
+        return "";
     }
-
-    return "";
-
 }
 
 void RocketChat::setCurrentChannel( const QString &pServerId, const QString &pCurrentChannel, const QString &pChannelName )
@@ -518,32 +490,28 @@ void RocketChat::setCurrentChannel( const QString &pServerId, const QString &pCu
     Q_UNUSED( pChannelName );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "setCurrentChannel", Q_ARG( QString, pCurrentChannel ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "setCurrentChannel", Q_ARG( QString, pCurrentChannel ) );
     }
 }
 
 void RocketChat::getNewVideoPath()
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "requestNewVideoPath" );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "requestNewVideoPath" );
     }
 }
 
 void RocketChat::setSetting( const QString &pKey, const QString &pValue )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "setSetting", Q_ARG( QString, pKey ), Q_ARG( QString, pValue ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "setSetting", Q_ARG( QString, pKey ), Q_ARG( QString, pValue ) );
     }
 }
 
 void RocketChat::getSetting( const QString &pKey )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "getSetting", Q_ARG( QString, pKey ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "getSetting", Q_ARG( QString, pKey ) );
     }
 }
 
@@ -569,8 +537,7 @@ void RocketChat::createAccount( const QString &serverId, const QString &email, c
 void RocketChat::markChannelAsRead( const QString &pChannelId )
 {
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "markChannelAsRead", Q_ARG( QString, pChannelId ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "markChannelAsRead", Q_ARG( QString, pChannelId ) );
     }
 }
 
@@ -579,8 +546,7 @@ void RocketChat::cancelUpload( const QString &pServerId, const QString &pFileId
     Q_UNUSED( pServerId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "cancelUpload", Q_ARG( QString, pFileId ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "cancelUpload", Q_ARG( QString, pFileId ) );
     }
 }
 
@@ -589,8 +555,7 @@ void RocketChat::logout( const QString &pServerId )
     Q_UNUSED( pServerId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "logout" );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "logout" );
         emit loggedOut( pServerId );
     }
 }
@@ -600,8 +565,7 @@ void RocketChat::createPublicGroup( const QString &pServerId, const QString &pCh
     Q_UNUSED( pServerId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "createPublicGroup", Q_ARG( QString, pChannelName ), Q_ARG( QStringList, pUsersNames ), Q_ARG( bool, pReadonly ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "createPublicGroup", Q_ARG( QString, pChannelName ), Q_ARG( QStringList, pUsersNames ), Q_ARG( bool, pReadonly ) );
     }
 }
 
@@ -610,8 +574,7 @@ void RocketChat::createPrivateGroup( const QString &pServerId, const QString &pC
     Q_UNUSED( pServerId );
 
     if ( mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(), "createPrivateGroup", Q_ARG( QString, pChannelName ), Q_ARG( QStringList, pUsersNames ), Q_ARG( bool, pReadonly ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(), "createPrivateGroup", Q_ARG( QString, pChannelName ), Q_ARG( QStringList, pUsersNames ), Q_ARG( bool, pReadonly ) );
     }
 }
 
@@ -638,8 +601,7 @@ void RocketChat::addLoginMethod( const QMap<QString, QVariant> &pMethod )
 
 void RocketChat::resetLoginMethods()
 {
-    auto result = QMetaObject::invokeMethod( Models::getLoginMethodsModel(), "clear" );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( Models::getLoginMethodsModel(), "clear" );
     //Models::getLoginMethodsModel()->clear();
 }
 
@@ -761,8 +723,7 @@ void RocketChat::serverReadySlot()
 
     connect( pServer, &RocketChatServerData::setting, this, &RocketChat::setting, Qt::UniqueConnection );
 
-    auto result = QMetaObject::invokeMethod( pServer, "init" );
-    Q_ASSERT( result );
+    QMetaObject::invokeMethod( pServer, "init" );
 }
 
 void RocketChat::storageReadySlot()
@@ -774,7 +735,7 @@ void RocketChat::storageReadySlot()
 //TODO: do this in a clean way
 void RocketChat::openAndroidFileDialog( QString channelId )
 {
-    currentChannel = std::move( channelId );
+    currentChannel = channelId;
 
     if ( mAndroidFileDialog == nullptr ) {
         mAndroidFileDialog = new AndroidFileDialog();
@@ -815,8 +776,7 @@ void RocketChat::openFileNameReady( const QString &pFile )
     if ( pFile == "null" ) {
         emit error( QStringLiteral( "invalid file information" ) );
     } else if ( !pFile.isEmpty() && mServerStatus ) {
-        auto result = QMetaObject::invokeMethod( mServerMap.first(),  "uploadFile", Q_ARG( QString, mCurrentChannel ), Q_ARG( QString, pFile ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( mServerMap.first(),  "uploadFile", Q_ARG( QString, mCurrentChannel ), Q_ARG( QString, pFile ) );
     }
 }
 
@@ -863,8 +823,7 @@ void RocketChat::onExternalChannelSwitchRequest( const QString &pName, const QSt
 {
     if ( mServerStatus ) {
         auto server = mServerMap.first();
-        auto result = QMetaObject::invokeMethod( server, "switchChannelByName", Q_ARG( QString, pName ), Q_ARG( QString, pType ) );
-        Q_ASSERT( result );
+        QMetaObject::invokeMethod( server, "switchChannelByName", Q_ARG( QString, pName ), Q_ARG( QString, pType ) );
         mChannelToSwitchTo.clear();
         mChannelToSwitchToType.clear();
     } else {
@@ -889,13 +848,11 @@ void RocketChat::onOnlineStateChanged( bool pOnline )
         if ( pOnline ) {
 
             for ( const auto &server : mServerMap ) {
-                auto result = QMetaObject::invokeMethod( server,  "resume" );
-                Q_ASSERT( result );
+                QMetaObject::invokeMethod( server,  "resume" );
             }
         } else {
             for ( const auto &server : mServerMap ) {
-                auto result = QMetaObject::invokeMethod( server, "setConnectionState", Q_ARG( ConnectionState, ConnectionState::OFFLINE ) );
-                Q_ASSERT( result );
+                QMetaObject::invokeMethod( server, "setConnectionState", Q_ARG( ConnectionState, ConnectionState::OFFLINE ) );
             }
 
             emit offline();
@@ -906,13 +863,14 @@ void RocketChat::onOnlineStateChanged( bool pOnline )
 void RocketChat::onApplicationStateChanged( const Qt::ApplicationState &pState )
 {
     if ( pState == Qt::ApplicationActive && mServerStatus ) {
+        QDateTime date;
         qDebug() << "application changed to active";
-        qDebug() << "time: " << QDateTime::currentDateTime();
+        qDebug() << "time: " << date.currentDateTime();
         qDebug() << "initialized: " << mInitialized;
         qDebug() << "networkconfig: " << mNetworkConfiguration.isOnline();
         //checks if a networkconnection is available
 
-        mInitialized = true;
+        mInitialized = 1;
 
         if ( mInitialized && mNetworkConfiguration.isOnline() ) {
             qDebug() << "network connection active";
@@ -920,21 +878,19 @@ void RocketChat::onApplicationStateChanged( const Qt::ApplicationState &pState )
             for ( const auto server : mServerMap ) {
 
                 //check if websocket connection is still alive, and if DDP is timedout
-                auto result = QMetaObject::invokeMethod( server, "onStateChanged", Q_ARG( Qt::ApplicationState, pState ) );
-                Q_ASSERT( result );
+                QMetaObject::invokeMethod( server, "onStateChanged", Q_ARG( Qt::ApplicationState, pState ) );
             }
         } else {
-            mInitialized = true;
+            mInitialized = 1;
         }
     } else if ( ( ( pState == Qt::ApplicationInactive ) || pState == Qt::ApplicationSuspended ) && mServerStatus ) {
         qDebug() << "away";
 
         if ( mNetworkConfiguration.isOnline() ) {
             for ( auto server : mServerMap ) {
-                auto result = QMetaObject::invokeMethod( server, "setUserPresenceStatus", Q_ARG( int, 2 ) );
-                Q_ASSERT( result );
-                result = QMetaObject::invokeMethod( server,  "disconnectFromServer" );
-                Q_ASSERT( result );
+                QMetaObject::invokeMethod( server, "setUserPresenceStatus", Q_ARG( int, 2 ) );
+                QMetaObject::invokeMethod( server,  "disconnectFromServer" );
+
             }
         }
     }
diff --git a/rocketchatserver.cpp b/rocketchatserver.cpp
index b5015ae..fbd050e 100755
--- a/rocketchatserver.cpp
+++ b/rocketchatserver.cpp
@@ -1073,7 +1073,7 @@ void RocketChatServerData::getFileRessource( const QString &pUrl )
 
 void RocketChatServerData::getFileRessource( const QString &pUrl, const QString &pType )
 {
-    bool showInline = false;
+    auto showInline = false;
 
     if ( pType == QStringLiteral( "temp" ) ) {
         showInline = true;
diff --git a/services/fileservice.cpp b/services/fileservice.cpp
index 0cd87a0..6394d99 100755
--- a/services/fileservice.cpp
+++ b/services/fileservice.cpp
@@ -77,6 +77,46 @@ bool FileService::getFileRessource( const QSharedPointer< FileRequest > &pReques
         auto tempFile = getFileFromCache( pRequest );
 
         if ( !tempFile.isNull() ) {
+            if ( !pRequest->showInline ) {
+                auto location = determineLocation( pRequest->url, pRequest->type, false );
+                QFile targetFile( location );
+
+                if ( targetFile.exists() ) {
+                    auto parts = location.split( "." );
+                    location.clear();
+
+                    for ( auto i = 0 ; i < ( parts.length() - 1 ); i++ ) {
+                        location += parts[i];
+
+                        if ( i < ( parts.length() - 1 ) ) {
+                            location += QStringLiteral( "." );
+                        }
+                    }
+
+                    location += QStringLiteral( "_" ) + QString::number( QDateTime::currentSecsSinceEpoch() );
+                    location += QStringLiteral( "." ) + parts[parts.size() - 1];
+
+                    QFile oldFile( tempFile->getFilePath() );
+
+                    if ( oldFile.copy( location ) ) {
+                        tempFile = QSharedPointer<TempFile>::create( location, pRequest->url );
+                    } else {
+                        qWarning() << oldFile.errorString();
+                    }
+
+                } else {
+                    QFile oldFile( tempFile->getFilePath() );
+
+                    if ( oldFile.copy( location ) ) {
+                        tempFile = QSharedPointer<TempFile>::create( location, pRequest->url );
+                    } else {
+                        qWarning() << oldFile.errorString();
+                    }
+
+                }
+
+            }
+
             pRequest->then( tempFile, pRequest->showInline );
         } else {
             getFileFromServer( pRequest );
@@ -120,8 +160,8 @@ QSharedPointer<TempFile> FileService::getFileFromCache( const QSharedPointer< Fi
 void FileService::getFileFromServer( const QSharedPointer< FileRequest > &pRequest )
 {
     if ( Q_LIKELY( !pRequest.isNull() ) ) {
-        QString baseUrl = mServer->getRestApi()->getBaseUrl();
-        QString fullUrl = baseUrl + pRequest->url ;
+        auto baseUrl = mServer->getRestApi()->getBaseUrl();
+        auto fullUrl = baseUrl + pRequest->url ;
 
         if ( !mCurrentDownloads.contains( fullUrl ) ) {
             RestRequestCallback success = [ = ]( QNetworkReply * pReply, const QJsonObject & pData, RestApi * api ) {
@@ -129,17 +169,26 @@ void FileService::getFileFromServer( const QSharedPointer< FileRequest > &pReque
                 Q_UNUSED( api );
 
                 if ( pReply ) {
-                    QByteArray content = pReply->readAll();
-                    QMimeType mimetype = mMimeDb.mimeTypeForData( content );
-                    QString location = determineLocation( pReply->url(), mimetype );
+                    auto content = pReply->readAll();
+
+                    QString location;
+
+                    //special treatment for avatars as RocketChat does server avatars always as .jpg even if they are svgs
+                    if ( pRequest->url.startsWith( QStringLiteral( "/avatar/" ) ) ) {
+                        auto mimetype = mMimeDb.mimeTypeForData( content );
+                        location = determineAvatarLocation( pReply->url(), mimetype );
+                    } else {
+                        location = determineLocation( pReply->url(), pRequest->type, pRequest->showInline );
+                    }
+
                     QUrl locationUrl( location );
-                    QString dirPath = locationUrl.adjusted( QUrl::RemoveFilename ).toString();
-                    QStringList parts = location.split( '/' );
+                    auto dirPath = locationUrl.adjusted( QUrl::RemoveFilename ).toString();
+                    auto parts = location.split( '/' );
 
                     QDir dir( dirPath );
 
                     if ( !dir.exists() ) {
-                        QString tempPath = parts.first();
+                        auto tempPath = parts.first();
 
                         for ( int i = 1; i < parts.length() - 1; i++ ) {
                             tempPath.append( '/' + parts[i] );
@@ -156,6 +205,8 @@ void FileService::getFileFromServer( const QSharedPointer< FileRequest > &pReque
                         QFile file( location );
                         QString url = pReply->url().toString();
 
+                        bool writeContent = true;
+
                         if ( file.exists() ) {
                             QString fileHash = getFileHash( &file );
                             QString dataHash = QCryptographicHash::hash( content, QCryptographicHash::Md5 );
@@ -165,23 +216,34 @@ void FileService::getFileFromServer( const QSharedPointer< FileRequest > &pReque
                                 pRequest->then( tempfile, pRequest->showInline );
 
                                 if ( location.size() ) {
-                                    mStorage->addFileCacheEntry( url, location );
+                                    if ( pRequest->showInline ) {
+                                        mStorage->addFileCacheEntry( url, location );
+                                    }
+
                                     mCurrentDownloads.remove( fullUrl );
                                 }
 
+                                writeContent = false;
+
                                 return;
                             }
                         }
 
-                        if ( file.open( QIODevice::ReadWrite ) ) {
+                        file.close();
+
+                        if ( writeContent && file.open( QIODevice::ReadWrite ) ) {
                             auto written = file.write( content );
                             qDebug() << "wrote byte to file" << written;
                             file.close();
                             auto tempfile = QSharedPointer<TempFile>::create( location, url );
-                            mStorage->addFileCacheEntry( url, location );
+
+                            if ( pRequest->showInline ) {
+                                mStorage->addFileCacheEntry( url, location );
+                            }
+
                             pRequest->then( tempfile, pRequest->showInline );
 
-                        } else {
+                        } else if ( writeContent ) {
                             qWarning() << "Could not write file" + location;
                             qWarning() << file.errorString();
                         }
@@ -225,38 +287,43 @@ QString FileService::getFileHash( QFile *pFile )
     return hashString;
 }
 
-QString FileService::determineLocation( const QUrl &pUrl, const QMimeType &pType )
+
+QString FileService::determineLocation( const QUrl &pUrl, const QString &pType, bool pShowInline )
 {
-    QString mimeTypeName = pType.name();
-    QString urlString = pUrl.toString();
-    bool image = mimeTypeName.contains( QStringLiteral( "image" ) );
-    bool video = mimeTypeName.contains( QStringLiteral( "video" ) );
-    bool audio = mimeTypeName.contains( QStringLiteral( "audio" ) );
-    int hits = image + video + audio;
-    QString urlPath = QStringLiteral( "/rocketChat" ) + pUrl.path();
+    auto urlPath = QStringLiteral( "/rocketChat" ) + pUrl.path();
     QString filePath;
 
-    if ( hits > 1 ) {
-        qDebug() << "More than one hit for one file" << urlString;
-    }
-
-    //Checks for wrongly named svg… please dont ask
-
-    if ( image ) {
-        filePath = mImagepath + urlPath;
-    } else if ( video ) {
-        filePath = mVideoPath + urlPath;
-    } else if ( audio ) {
-        filePath = mMusicPath + urlPath;
+    if ( !pShowInline ) {
+        if ( pType == "image" ) {
+            filePath = mImagepath + urlPath;
+        } else if ( pType == "video" ) {
+            filePath = mVideoPath + urlPath;
+        } else if ( pType == "music" ) {
+            filePath = mMusicPath + urlPath;
+        } else if ( pType == "document" ) {
+            filePath = mDocumentPath + urlPath;
+        }
     } else {
         filePath = mTempPath + urlPath;
     }
 
+    return filePath;
+}
+
+QString FileService::determineAvatarLocation( const QUrl &pUrl, const QMimeType &pType )
+{
+    QString mimeTypeName = pType.name();
+    QString urlString = pUrl.toString();
+    QString urlPath = QStringLiteral( "/rocketChat" ) + pUrl.path();
+    QString filePath;
+
+    filePath = mTempPath + urlPath;
+
     if ( pType.name().contains( "svg" ) ) {
         QStringList parts = filePath.split( "." );
 
         //change ending to correct ending if mimetype and ending collide
-        if ( !parts.isEmpty() && parts.last() == "jpg" ) {
+        if ( !parts.isEmpty() && parts.last() == QStringLiteral( "jpg" ) ) {
             QString origSuffix = parts.last();
             QString suffix = pType.preferredSuffix();
             qDebug() << "origSuffix " << origSuffix;
diff --git a/services/fileservice.h b/services/fileservice.h
index d72490c..96c4540 100644
--- a/services/fileservice.h
+++ b/services/fileservice.h
@@ -54,7 +54,8 @@ class FileService
         RocketChatServerData *mServer;
         PersistanceLayer *mStorage;
         QMimeDatabase mMimeDb;
-        QString determineLocation( const QUrl &url, const QMimeType &type );
+        QString determineAvatarLocation( const QUrl &pUrl, const QMimeType &pType );
+        QString determineLocation( const QUrl &pUrl, const QString &pType, bool pShowInline = true );
         QString mImagepath;
         QString mVideoPath;
         QString mDocumentPath;
-- 
GitLab