extension_forms.py 12.6 KB
Newer Older
Cédric Bellegarde's avatar
Cédric Bellegarde committed
1
# Copyright (c) 2017-2018 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
2 3 4 5 6 7 8 9 10 11 12
# 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 3 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, see <http://www.gnu.org/licenses/>.

13
from gi.repository import WebKit2WebExtension, GLib, GObject
Cédric Bellegarde's avatar
Cédric Bellegarde committed
14

15 16
from urllib.parse import urlparse

17
from eolie.define import App
18
from eolie.helper_passwords import PasswordsHelper
19
from eolie.logger import Logger
20 21


22
class FormsExtension(GObject.Object):
23 24 25 26
    """
        Handle forms prefill
    """

27 28 29 30
    __gsignals__ = {
        'submit-form': (GObject.SignalFlags.RUN_FIRST, None, (GLib.Variant,))
    }

31
    def __init__(self, extension):
32 33 34 35
        """
            Connect wanted signal
            @param extension as WebKit2WebExtension
        """
36
        GObject.Object.__init__(self)
37
        self.__helper = PasswordsHelper()
38
        self.__extension = extension
39
        self.__elements_uri = None
40 41
        self.__pending_credentials = None
        self.__page_id = None
42 43
        extension.connect("page-created", self.__on_page_created)

44
    def set_credentials(self, form, webpage):
45 46
        """
            Set credentials on page
47 48 49 50
            @param form as {
                           "element":WebKit2WebExtension.DOMHTMLFormElement,
                           "username": WebKit2WebExtension.DOMHTMLInputElement,
                           "password": WebKit2WebExtension.DOMHTMLInputElement}
51 52
            @param webpage as WebKit2WebExtension.WebPage
        """
53
        if App().settings.get_value("remember-passwords"):
54 55 56 57
            form_input_username = form["username"].get_name()
            form_input_password = form["password"].get_name()
            if form_input_username is not None and\
                    form_input_password is not None:
58
                self.__helper.get(self.get_form_uri(form["element"]),
59 60 61 62 63
                                  form_input_username,
                                  form_input_password,
                                  self.set_input_forms,
                                  webpage,
                                  form)
64

65
    def set_input_forms(self, attributes, password,
66
                        uri, index, count, webpage, form, username=None):
67
        """
Cédric Bellegarde's avatar
Cédric Bellegarde committed
68
            Set login/password input
69 70 71
            @param attributes as {}
            @param password as str
            @param uri as str
72 73
            @param index as int
            @param count as int
74
            @param webpage as WebKit2WebExtension.WebPage
75 76 77 78
            @param form as {
                           "element":WebKit2WebExtension.DOMHTMLFormElement,
                           "username": WebKit2WebExtension.DOMHTMLInputElement,
                           "password": WebKit2WebExtension.DOMHTMLInputElement}
79
            @param username as str
80
        """
81 82
        if attributes is None:
            return
83
        # We only set first available password
84
        if (index != 0 or count > 1) and username is None:
85
            return
86
        parsed = urlparse(self.get_form_uri(form["element"]))
87
        # Allow unsecure completion if wanted by user
88
        if parsed.scheme != "https" and username is None:
89
            return
90 91
        # We want a user, check if it wanted password
        if username is not None and username != attributes["login"]:
92 93
            return
        try:
94 95
            form["username"].set_value(attributes["login"])
            form["password"].set_value(password)
96
        except Exception as e:
97
            Logger.error("FormsExtension::set_input_forms(): %s", e)
98

99
    def get_elements(self, elements):
100
        """
101
            Get forms as dict and textareas for elements
102
            @param elements as [WebKit2WebExtension.DOMElement]
103 104 105 106 107
            @return elements as
                ([{"element":WebKit2WebExtension.DOMHTMLFormElement,
                   "username": WebKit2WebExtension.DOMHTMLInputElement,
                   "password": WebKit2WebExtension.DOMHTMLInputElement}],
                 [WebKit2WebExtension.DOMHTMLTextAreaElement])
108
        """
109 110
        forms = []
        textareas = []
111 112
        for element in elements:
            if isinstance(element, WebKit2WebExtension.DOMHTMLTextAreaElement):
113
                textareas.append(element)
114 115
            elif isinstance(element,
                            WebKit2WebExtension.DOMHTMLFormElement):
116 117
                form = {"element": element}
                elements_collection = element.get_elements()
Cédric Bellegarde's avatar
Cédric Bellegarde committed
118 119 120
                h = 0
                while h < elements_collection.get_length():
                    element = elements_collection.item(h)
121 122 123
                    if isinstance(element,
                                  WebKit2WebExtension.DOMHTMLInputElement):
                        if element.get_input_type() == "password" and\
124 125
                                element.get_name() is not None and\
                                "password" not in form.keys():
126 127 128 129
                            form["password"] = element
                        elif element.get_input_type() in ["text",
                                                          "email",
                                                          "search"] and\
130 131
                                element.get_name() is not None and\
                                "username" not in form.keys():
132
                            form["username"] = element
133
                    elif isinstance(
Cédric Bellegarde's avatar
Cédric Bellegarde committed
134 135
                            element,
                            WebKit2WebExtension.DOMHTMLTextAreaElement):
136
                        textareas.append(element)
Cédric Bellegarde's avatar
Cédric Bellegarde committed
137
                    h += 1
138
                keys = form.keys()
139
                if "username" in keys and "password" in keys:
140 141
                    forms.append(form)
        return (forms, textareas)
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
    def get_hostname_uri(self, page):
        """
            Get form uri for page
            @param page as WebKit2WebExtension.WebPage
            @return str
            @raise Exception
        """
        page = self.__extension.get_page(self.__page_id)
        if page is None:
            raise Exception("Can't find page!")
        uri = page.get_uri()
        parsed = urlparse(uri)
        return "%s://%s" % (parsed.scheme, parsed.netloc)

    def get_form_uri(self, form):
        """
            Get form uri for form
160
            @param form as WebKit2WebExtension.DOMHTMLFormElement
161 162
            @return str
        """
163
        form_uri = form.get_action()
164 165 166 167 168 169 170 171
        if form_uri is None:
            page = self.__extension.get_page(self.__page_id)
            return self.get_hostname_uri(page)
        else:
            parsed_form_uri = urlparse(form_uri)
            return "%s://%s" % (parsed_form_uri.scheme,
                                parsed_form_uri.netloc)

172 173 174 175
    @property
    def pending_credentials(self):
        """
            Get credentials
176
            @return (str, str, str, str, str, str) or None
177 178
        """
        return self.__pending_credentials
179

180 181 182
#######################
# PRIVATE             #
#######################
183 184
    def __on_get_password(self, attributes, password, form_uri, index, count,
                          user_form_name, user_form_value, pass_form_name,
185
                          pass_form_value, hostname_uri, page_id):
186 187 188 189 190 191 192 193 194 195 196
        """
            Ask for credentials through DBus
            @param attributes as {}
            @param password as str
            @param form_uri as str
            @param index as int
            @param count as int
            @param user_form_name as str
            @param user_form_value as str
            @param pass_form_name as str
            @param pass_form_value as str
197
            @param hostname_uri as str
198 199 200
            @param page_id as int
        """
        try:
201 202 203 204 205 206 207 208
            self.__pending_credentials = (user_form_name,
                                          user_form_value,
                                          pass_form_name,
                                          pass_form_value,
                                          hostname_uri,
                                          form_uri)

            # New credential
209 210 211 212 213 214
            if count == 0:
                args = ("", user_form_name, user_form_value,
                        pass_form_name, hostname_uri, form_uri)
                variant = GLib.Variant.new_tuple(GLib.Variant("(ssssss)",
                                                              args))
                self.emit("submit-form", variant)
215
            # Last credential
216
            elif index == count - 1:
217 218 219 220 221 222 223 224 225 226 227 228 229 230
                if attributes is not None:
                    uuid = attributes["uuid"]
                    # No password change
                    if attributes["login"] == user_form_value and\
                            password == pass_form_value:
                        return
                    # New password
                    elif attributes["login"] != user_form_value:
                        uuid = ""
                args = (uuid, user_form_name, user_form_value,
                        pass_form_name, hostname_uri, form_uri)
                variant = GLib.Variant.new_tuple(GLib.Variant("(ssssss)",
                                                              args))
                self.emit("submit-form", variant)
231
        except Exception as e:
232
            Logger.error("FormsExtension::__on_get_password(): %s", e)
233

234 235 236 237
    def __on_will_submit_form(self, webpage, form, step,
                              source, target, names, values):
        """
            @param webpage as WebKit2WebExtension.WebPage
238
            @param form as WebKit2WebExtension.DOMHTMLFormElement
239 240 241 242 243 244
            @param step as WebKit2WebExtension.FormSubmissionStep
            @param source as WebKit2WebExtension.Frame
            @param target as WebKit2WebExtension.Frame
            @param names as [str]
            @param values as [str]
        """
245 246
        if step != WebKit2WebExtension.FormSubmissionStep.SEND_DOM_EVENT or\
                not names or not values:
247
            return
Cédric Bellegarde's avatar
Cédric Bellegarde committed
248
        try:
249
            # Check elements
250
            self.__pending_credentials = None
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
            document = webpage.get_dom_document()
            username_idx = None
            password_idx = None
            idx = 0
            for name in names:
                if username_idx is not None and password_idx is not None:
                    break
                elements = document.get_elements_by_name(name)
                for elements_idx in range(0, elements.get_length()):
                    element = elements.item(elements_idx)
                    if isinstance(element,
                                  WebKit2WebExtension.DOMHTMLInputElement):
                        if element.get_input_type() == "password" and\
                                element.get_name() is not None:
                            password_idx = idx
                            break
                        elif element.get_input_type() in ["text",
                                                          "email",
                                                          "search"] and\
                                element.get_name() is not None:
                            username_idx = idx
                            break
                idx += 1
            if username_idx is not None and password_idx is not None:
                hostname_uri = self.get_hostname_uri(webpage)
                form_uri = self.get_form_uri(form)
                user_form_name = names[username_idx]
                user_form_value = values[username_idx]
                pass_form_name = names[password_idx]
                pass_form_value = values[password_idx]
                self.__helper.get(form_uri, user_form_name,
                                  pass_form_name, self.__on_get_password,
                                  user_form_name, user_form_value,
                                  pass_form_name, pass_form_value,
                                  hostname_uri,
                                  self.__page_id)
Cédric Bellegarde's avatar
Cédric Bellegarde committed
287
        except Exception as e:
Cédric Bellegarde's avatar
Cédric Bellegarde committed
288
            Logger.error("FormsExtension::__on_will_submit_form(): %s" % e)
289

290 291 292 293 294 295
    def __on_page_created(self, extension, webpage):
        """
            Connect to send request
            @param extension as WebKit2WebExtension
            @param webpage as WebKit2WebExtension.WebPage
        """
296
        self.__page_id = webpage.get_id()
297
        webpage.connect("will-submit-form", self.__on_will_submit_form)