Example #1
0
 def restore_cookies(self):
     if os.path.exists(self.cookie_path):
         with open(self.cookie_path, 'r') as f:
             lines = ''
             for line in f:
                 lines = lines + line
                 allCookies = QNetworkCookie.parseCookies(lines)
                 QNetworkCookieJar.setAllCookies(self, allCookies)
Example #2
0
def setup():
    global incognito_cookie_jar
    global cookie_jar
    global network_access_manager
    global incognito_network_access_manager
    cookie_jar = QNetworkCookieJar(QCoreApplication.instance())
    incognito_cookie_jar = QNetworkCookieJar(QCoreApplication.instance())
    network_access_manager = NetworkAccessManager()
    network_access_manager.setCookieJar(cookie_jar)
    incognito_network_access_manager = NetworkAccessManager(nocache=True)
    incognito_network_access_manager.setCookieJar(incognito_cookie_jar)
Example #3
0
 def __init__(self):
     super().__init__()
     self.setWindowIcon(QIcon(app_icon))
     self.setWindowTitle('login')
     self.loadFinished.connect(self.process_load_finish)
     self.main_window = None
     self.is_login = False
     cookie_store = self.page().profile().cookieStore()
     print(cookie_store)
     self.cookiejar = QNetworkCookieJar()
     cookie_store.cookieAdded.connect(self.cookie_added)
     self.login_on_startup()
Example #4
0
def cookiejar_and_cache():
    """Fixture providing a fake cookie jar and cache."""
    jar = QNetworkCookieJar()
    cache = FakeNetworkCache()
    objreg.register('cookie-jar', jar)
    objreg.register('cache', cache)
    yield
    objreg.delete('cookie-jar')
    objreg.delete('cache')
Example #5
0
 def save_cookies(self):
     allCookies = QNetworkCookieJar.allCookies(self)
     
     cookie_dir = os.path.dirname(self.cookie_path)
     if not os.path.exists(cookie_dir):
         os.makedirs(cookie_dir)
         
     with open(self.cookie_path, 'w') as f:
         lines = ''
         for cookie in allCookies:
             lines = lines + cookie.toRawForm() + '\r\n'
             f.writelines(lines)
Example #6
0
def cookiejar_and_cache(stubs):
    """Fixture providing a fake cookie jar and cache."""
    jar = QNetworkCookieJar()
    ram_jar = cookies.RAMCookieJar()
    cache = stubs.FakeNetworkCache()
    objreg.register('cookie-jar', jar)
    objreg.register('ram-cookie-jar', ram_jar)
    objreg.register('cache', cache)
    yield
    objreg.delete('cookie-jar')
    objreg.delete('ram-cookie-jar')
    objreg.delete('cache')
Example #7
0
class CookieStore(object):
    def __init__(self):
        self._cookie_jar = QNetworkCookieJar()

    def add(self, cookie_dict, scheme, hostname, path="/"):
        cookie_list = []
        for key, value in cookie_dict.items():
            cookie = QNetworkCookie()
            cookie.setDomain(hostname)
            cookie.setPath(path)
            key_b = QByteArray()
            key_b.append(key)
            cookie.setName(key_b)
            value_b = QByteArray()
            value_b.append(value)
            cookie.setValue(value_b)
            cookie_list.append(cookie)
        self._cookie_jar.setCookiesFromUrl(cookie_list, QUrl(str(scheme)))

    def get(self, url):
        cookie_list = self._cookie_jar.cookiesForUrl(QUrl(url))
        cookie_dict = {}
        for cookie in cookie_list:
            cookie_dict[cookie.name()] = cookie.value()
        return cookie_dict

    def clear(self, url):
        cookie_list = self._cookie_jar.cookiesForUrl(QUrl(url))
        for cookie in cookie_list:
            cookie.setValue("")
        self._cookie_jar.setCookiesFromUrl(cookie_list, QUrl(url))
Example #8
0
 def cookiesForUrl(self, url):
     """
     Public method to get the cookies for a URL.
     
     @param url URL to get cookies for (QUrl)
     @return list of cookies (list of QNetworkCookie)
     """
     if not self.__loaded:
         self.load()
     
     globalSettings = QWebSettings.globalSettings()
     if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
         return []
     
     return QNetworkCookieJar.cookiesForUrl(self, url)
Example #9
0
    def cookiesForUrl(self, url):
        """
        Public method to get the cookies for a URL.
        
        @param url URL to get cookies for (QUrl)
        @return list of cookies (list of QNetworkCookie)
        """
        if not self.__loaded:
            self.load()

        globalSettings = QWebSettings.globalSettings()
        if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
            return []

        return QNetworkCookieJar.cookiesForUrl(self, url)
Example #10
0
    def set_cookies_from_url(self, cookies, url):
        """ Reimplementation from base class. Prevents cookies from being set
        if not from whitelisted domains.

        """
        (_, domain, suffix) = extract(url.host())
        site = domain + '.' + suffix

        if site not in self.allowed:
            if self.parent().show_detail:
                print("COOKIE FROM {} not set".format(url.toString()))  # COO01
            ret = []
        else:
            print("SET COOKIE FROM {}".format(url.toString()))
            ret = cookies

        return QNetworkCookieJar.setCookiesFromUrl(self, ret, url)
Example #11
0
    def set_cookies_from_url(self, cookies, url):
        """ Reimplementation from base class. Prevents cookies from being set
        if not from whitelisted domains.

        """
        (_, domain, suffix) = extract(url.host())
        site = domain + '.' + suffix

        if site not in self.allowed:
            if self.parent().show_detail:
                print("COOKIE FROM {} not set".format(url.toString()))  # COO01
            ret = []
        else:
            print("SET COOKIE FROM {}".format(url.toString()))
            ret = cookies

        return QNetworkCookieJar.setCookiesFromUrl(self, ret, url)
Example #12
0
 def __init__(self, parent):
     super().__init__(parent)
     self.set_url('http://google.ru')
     conn = QNetworkAccessManager()
     self.conn = conn
     self.r = QNetworkRequest()
     self.r.attribute(QNetworkRequest.CookieSaveControlAttribute, QVariant(True))
     # self.r.setHeader(QNetworkRequest.ContentTypeHeader, "application/x-www-form-urlencoded")
     # self.r.setRawHeader("Referer", "http://www.facebook.com/")
     # self.r.setRawHeader("Host", "www.facebook.com")
     self.cj = QNetworkCookieJar()
     conn.setCookieJar(self.cj)
     conn.createRequest = self._create_request
     self.wv = WebView()
     self.wv.show()
     self.wv.page().setNetworkAccessManager(conn)
     # self.wv.auth()
     self.loop = QEventLoop()
     pass
Example #13
0
 def setCookiesFromUrl(self, cookieList, url):
     """
     Public method to set cookies for a URL.
     
     @param cookieList list of cookies to set (list of QNetworkCookie)
     @param url url to set cookies for (QUrl)
     @return flag indicating cookies were set (boolean)
     """
     if not self.__loaded:
         self.load()
     
     globalSettings = QWebSettings.globalSettings()
     if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
         return False
     
     host = url.host()
     eBlock = self.__isOnDomainList(self.__exceptionsBlock, host)
     eAllow = not eBlock and \
         self.__isOnDomainList(self.__exceptionsAllow, host)
     eAllowSession = not eBlock and \
         not eAllow and \
         self.__isOnDomainList(
             self.__exceptionsAllowForSession, host)
     
     addedCookies = False
     acceptInitially = self.__acceptCookies != self.AcceptNever
     if (acceptInitially and not eBlock) or \
        (not acceptInitially and (eAllow or eAllowSession)):
         # url domain == cookie domain
         soon = QDateTime.currentDateTime()
         soon = soon.addDays(90)
         for cookie in cookieList:
             lst = []
             if not (self.__filterTrackingCookies and
                     cookie.name().startsWith(b"__utm")):
                 if eAllowSession:
                     cookie.setExpirationDate(QDateTime())
                 if self.__keepCookies == self.KeepUntilTimeLimit and \
                    not cookie.isSessionCookie and \
                    cookie.expirationDate() > soon:
                     cookie.setExpirationDate(soon)
                 lst.append(cookie)
                 if QNetworkCookieJar.setCookiesFromUrl(self, lst, url):
                     addedCookies = True
                 elif self.__acceptCookies == self.AcceptAlways:
                     # force it in if wanted
                     cookies = self.allCookies()
                     for ocookie in cookies[:]:
                         # does the cookie exist already?
                         if cookie.name() == ocookie.name() and \
                            cookie.domain() == ocookie.domain() and \
                            cookie.path() == ocookie.path():
                             # found a match
                             cookies.remove(ocookie)
                     
                     cookies.append(cookie)
                     self.setAllCookies(cookies)
                     addedCookies = True
     
     if addedCookies:
         self.__saveTimer.changeOccurred()
         self.cookiesChanged.emit()
     
     return addedCookies
Example #14
0
def cookiejar_and_cache(stubs, monkeypatch):
    """Fixture providing a fake cookie jar and cache."""
    monkeypatch.setattr(cookies, 'cookie_jar', QNetworkCookieJar())
    monkeypatch.setattr(cookies, 'ram_cookie_jar', cookies.RAMCookieJar())
    monkeypatch.setattr(cache, 'diskcache', stubs.FakeNetworkCache())
Example #15
0
 def __init__(self, cookies, qt_url, parent=None):
     QNetworkCookieJar.__init__(self, parent)
     for cookie in cookies:
         QNetworkCookieJar.setCookiesFromUrl(
             self,
             QNetworkCookie().parseCookies(QByteArray(cookie)), qt_url)
Example #16
0
 def allCookies(self):
     return QNetworkCookieJar.allCookies(self)
Example #17
0
 def __init__(self, parent = None):
     QNetworkCookieJar.__init__(self, parent)
     self.cookie_path = os.path.expanduser("~/.emacs.d/deepin-emacs/webkit-cookies")
Example #18
0
 def get_cookies(self):
     cookie_jar = QNetworkCookieJar()
     for item in self.cookies:
         cookie_jar.insertCookie(item.get_qnetwork_cookie())
     return cookie_jar.allCookies()
Example #19
0
 def setAllCookies(self, cookie_list, network_cookie=None):
     QNetworkCookieJar.setAllCookies(self, cookie_list, network_cookie)
Example #20
0
class LoginWindow(QWebEngineView):
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QIcon(app_icon))
        self.setWindowTitle('login')
        self.loadFinished.connect(self.process_load_finish)
        self.main_window = None
        self.is_login = False
        cookie_store = self.page().profile().cookieStore()
        print(cookie_store)
        self.cookiejar = QNetworkCookieJar()
        cookie_store.cookieAdded.connect(self.cookie_added)
        self.login_on_startup()

    def set_main_window(self, main_window):
        self.main_window = main_window

    def show(self):
        self.load(QUrl(longzhu_login_url))
        super().show()

    def process_load_finish(self):
        if self.url().host() == 'www.longzhu.com' and self.url().path() == '/':
            print('after login')
            self.page().toHtml(self.login)

    def login(self, data):
        try:
            self.login_html = data
            user_menu = pq(data)('#topbar-user-menu')
            self.level = user_menu.find('i.user-lv').attr['class'].split(
                '-')[-1]
            self.uid = user_menu.find(
                'a.report-rbi-click').attr['data-label'].split(':')[-1]
            self.username = user_menu.find('span.topbar-username').text()
            self.is_login = True
            print(self.level)
            print(self.uid)
            print(self.username)
            for cookie in self.cookiejar.cookiesForUrl(
                    QUrl(longzhu_login_url)):
                print('name = {}, value = {}'.format(
                    str(cookie.name(), encoding='ascii'),
                    str(cookie.value(), encoding='ascii')))
            self.main_window.login(self.username, self.level)
            self.load(QUrl(''))
            self.hide()
            self.save_cookie()
        except:
            pass

    def logout(self):
        self.level = ''
        self.uid = ''
        self.username = ''
        self.is_login = False
        self.cookiejar.setAllCookies([])
        self.page().profile().cookieStore().deleteAllCookies()
        self.delete_cookie()

    def login_on_startup(self):
        if self.load_cookie():
            self.load(QUrl('http://www.longzhu.com'))

    def cookie_added(self, cookie):
        if cookie.name() == b'p1u_id' or cookie.name() == b'PLULOGINSESSID':
            print('name = {}, domain = {}, value = {}, path = {}, date = {}'.
                  format(cookie.name(), cookie.domain(), cookie.value(),
                         cookie.path(),
                         cookie.expirationDate().date()))
        self.cookiejar.setCookiesFromUrl([cookie], QUrl(longzhu_login_url))

    def save_cookie(self):
        with open(cookie_file, 'wb') as f:
            for cookie in self.cookiejar.allCookies():
                f.write(cookie.toRawForm() + b'\n')

    def delete_cookie(self):
        try:
            os.remove(cookie_file)
        except OSError:
            pass

    def load_cookie(self):
        cookies = []
        if os.path.isfile(cookie_file):
            with open(cookie_file, 'rb') as f:
                for line in f:
                    cookie = QNetworkCookie.parseCookies(line)
                    self.cookiejar.setCookiesFromUrl(cookie,
                                                     QUrl(longzhu_login_url))
                    self.page().profile().cookieStore().setCookie(cookie[0])
                return True
        return False
Example #21
0
 def __init__(self):
     self._cookie_jar = QNetworkCookieJar()
Example #22
0
    def setCookiesFromUrl(self, cookieList, url):
        """
        Public method to set cookies for a URL.
        
        @param cookieList list of cookies to set (list of QNetworkCookie)
        @param url url to set cookies for (QUrl)
        @return flag indicating cookies were set (boolean)
        """
        if not self.__loaded:
            self.load()

        globalSettings = QWebSettings.globalSettings()
        if globalSettings.testAttribute(QWebSettings.PrivateBrowsingEnabled):
            return False

        host = url.host()
        eBlock = self.__isOnDomainList(self.__exceptionsBlock, host)
        eAllow = not eBlock and \
            self.__isOnDomainList(self.__exceptionsAllow, host)
        eAllowSession = not eBlock and \
            not eAllow and \
            self.__isOnDomainList(
                self.__exceptionsAllowForSession, host)

        addedCookies = False
        acceptInitially = self.__acceptCookies != self.AcceptNever
        if (acceptInitially and not eBlock) or \
           (not acceptInitially and (eAllow or eAllowSession)):
            # url domain == cookie domain
            soon = QDateTime.currentDateTime()
            soon = soon.addDays(90)
            for cookie in cookieList:
                lst = []
                if not (self.__filterTrackingCookies
                        and cookie.name().startsWith(b"__utm")):
                    if eAllowSession:
                        cookie.setExpirationDate(QDateTime())
                    if self.__keepCookies == self.KeepUntilTimeLimit and \
                       not cookie.isSessionCookie and \
                       cookie.expirationDate() > soon:
                        cookie.setExpirationDate(soon)
                    lst.append(cookie)
                    if QNetworkCookieJar.setCookiesFromUrl(self, lst, url):
                        addedCookies = True
                    elif self.__acceptCookies == self.AcceptAlways:
                        # force it in if wanted
                        cookies = self.allCookies()
                        for ocookie in cookies[:]:
                            # does the cookie exist already?
                            if cookie.name() == ocookie.name() and \
                               cookie.domain() == ocookie.domain() and \
                               cookie.path() == ocookie.path():
                                # found a match
                                cookies.remove(ocookie)

                        cookies.append(cookie)
                        self.setAllCookies(cookies)
                        addedCookies = True

        if addedCookies:
            self.__saveTimer.changeOccurred()
            self.cookiesChanged.emit()

        return addedCookies