summaryrefslogtreecommitdiff
path: root/kodereviewer/network_manager.py
blob: 2d8b8aa3b8035b11f111ae275baed06d69ea6322 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
from typing import Optional

from PySide6.QtCore import QObject, QSettings, Signal, Slot, Property, qDebug
from PySide6.QtNetwork import QHttpHeaders, QNetworkAccessManager, QNetworkReply, QNetworkRequestFactory
from PySide6.QtQml import QmlElement

from kodereviewer.project import Project

QML_IMPORT_NAME = "org.deprecated.kodereviewer"
QML_IMPORT_MAJOR_VERSION = 1

@QmlElement
class NetworkManager(QObject):

    _project: Optional[Project]
    _manager: QNetworkAccessManager
    _request_factory: QNetworkRequestFactory

    projectChanged = Signal()

    def __init__(self):
        super().__init__()
        self._project = None
        self._manager = QNetworkAccessManager()

        self._request_factory = QNetworkRequestFactory()
        settings = QSettings()
        github_token: str = str(settings.value("githubToken"))
        headers = QHttpHeaders()
        headers.append(QHttpHeaders.WellKnownHeader.Accept, "application/vnd.github+json")
        headers.append(QHttpHeaders.WellKnownHeader.Authorization,
                       f'Bearer {github_token}')
        headers.append(QHttpHeaders.WellKnownHeader.UserAgent, "kodereviewer")
        print(f'Authorization: Bearer {github_token}')
        self._request_factory.setCommonHeaders(headers)

        self._manager.finished.connect(self.reply_finished)

    def project(self) -> Optional[Project]:
        return self._project

    def set_project(self, project: Optional[Project]):
        if project is None:
            return
        self._project = project
        self.projectChanged.emit()

        base_url = f'https://api.github.com/repos/{self._project.owner}/{self._project.name}'
        self._request_factory.setBaseUrl(base_url)

    project = Property(Project, fget=project, fset=set_project)

    def reply_finished(self, reply: QNetworkReply):
        self._project.load_pull_requests(reply.readAll())

    @Slot()
    def getPullRequests(self) -> None:
        self._manager.get(self._request_factory.createRequest("/pulls"))