1 #ifndef SEAFILE_CLIENT_NETWORK_MANAGER_H
2 #define SEAFILE_CLIENT_NETWORK_MANAGER_H
3 
4 #include <QObject>
5 #include <vector>
6 #include <QNetworkReply>
7 #include <QMutex>
8 
9 #include "utils/singleton.h"
10 
11 class QNetworkAccessManager;
12 class QNetworkProxy;
13 class QTimer;
14 
15 class NetworkManager : public QObject {
16   Q_OBJECT
17 public:
instance()18     static NetworkManager* instance() {
19         if (!instance_) {
20             static NetworkManager singleton;
21             instance_ = &singleton;
22         }
23         return instance_;
24     }
25     void addWatch(QNetworkAccessManager* manager);
26     void applyProxy(const QNetworkProxy& proxy);
27     void reapplyProxy();
28 
29     // retry only once
shouldRetry(const QNetworkReply::NetworkError error)30     bool shouldRetry(const QNetworkReply::NetworkError error) {
31         if ((error == QNetworkReply::ProxyConnectionClosedError ||
32              error == QNetworkReply::ProxyConnectionRefusedError ||
33              error == QNetworkReply::ProxyNotFoundError ||
34              error == QNetworkReply::ProxyTimeoutError ||
35              error == QNetworkReply::UnknownProxyError) &&
36             should_retry_) {
37             NetworkManager::instance()->reapplyProxy();
38             should_retry_ = false;
39             return true;
40         }
41         return false;
42     }
43 
44 signals:
45     void proxyChanged(const QNetworkProxy& proxy);
46 
47 private slots:
48     void onCleanup();
49 
50 private:
51     std::vector<QNetworkAccessManager*> managers_;
52     NetworkManager();
~NetworkManager()53     ~NetworkManager() {}
54     NetworkManager(const NetworkManager&) /* = delete */ ;
55     bool should_retry_;
56     static NetworkManager* instance_;
57 };
58 
59 // Check the network connection periodically, and reset the qt
60 // QNetworkAccessManager if the network is reconnected.
61 class NetworkStatusDetector: public QObject
62 {
63     Q_OBJECT
64     SINGLETON_DEFINE(NetworkStatusDetector)
65 public:
66     ~NetworkStatusDetector();
67     void start();
68     void stop();
69     void setNetworkFailure(QNetworkReply::NetworkError err);
70     void setNetworkSuccess();
71 
72 public slots:
73     void detect();
74 
75 signals:
76     void check();
77 
78 private:
79     NetworkStatusDetector();
80     bool shouldTreatErrorAsNetworkReset(QNetworkReply::NetworkError error);
81     QMutex network_error_mutex_;
82 
83     QTimer *check_timer_;
84     bool has_network_failure_;
85 };
86 
87 
88 #endif // SEAFILE_CLIENT_NETWORK_MANAGER_H
89