|
1
|
|
|
import asyncio |
|
2
|
|
|
import base64 |
|
3
|
|
|
|
|
4
|
|
|
from .image import Image |
|
5
|
|
|
from ...tools import Tools |
|
6
|
|
|
|
|
7
|
|
|
""" |
|
8
|
|
|
Copyright (c) 2020 Star Inc.(https://starinc.xyz) |
|
9
|
|
|
|
|
10
|
|
|
This Source Code Form is subject to the terms of the Mozilla Public |
|
11
|
|
|
License, v. 2.0. If a copy of the MPL was not distributed with this |
|
12
|
|
|
file, You can obtain one at http://mozilla.org/MPL/2.0/. |
|
13
|
|
|
""" |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
class View: |
|
17
|
|
|
def __init__(self, pbp_handle): |
|
18
|
|
|
self.data_control = pbp_handle.data_control |
|
19
|
|
|
self.image_handle = Image(pbp_handle) |
|
20
|
|
|
|
|
21
|
|
|
async def analyze(self, target_url: str): |
|
22
|
|
|
""" |
|
23
|
|
|
Analyze URL |
|
24
|
|
|
|
|
25
|
|
|
:param target_url: URL |
|
26
|
|
|
:return: URLs similar to in trustlist |
|
27
|
|
|
""" |
|
28
|
|
|
(view_signature, view_data) = await self.image_handle.capture(target_url) |
|
29
|
|
|
|
|
30
|
|
|
signature_query = await self.image_handle.signature(view_signature) |
|
31
|
|
|
yield signature_query |
|
32
|
|
|
|
|
33
|
|
|
if signature_query: |
|
34
|
|
|
return |
|
35
|
|
|
|
|
36
|
|
|
query = {} |
|
37
|
|
|
async for url, score in self.image_handle.rank(view_data): |
|
38
|
|
|
query[url] = score |
|
39
|
|
|
|
|
40
|
|
|
for url in query: |
|
41
|
|
|
if query[url] > 0.9 and query[url] == max(query.values()): |
|
42
|
|
|
yield url |
|
43
|
|
|
|
|
44
|
|
|
async def generate(self): |
|
45
|
|
|
""" |
|
46
|
|
|
Generate samples |
|
47
|
|
|
|
|
48
|
|
|
:return: |
|
49
|
|
|
""" |
|
50
|
|
|
events = [] |
|
51
|
|
|
|
|
52
|
|
|
async def _upload(url: str): |
|
53
|
|
|
""" |
|
54
|
|
|
Child function, to upload data to database |
|
55
|
|
|
|
|
56
|
|
|
:param url: URL |
|
57
|
|
|
:return: |
|
58
|
|
|
""" |
|
59
|
|
|
try: |
|
60
|
|
|
(view_signature, view_data) = await self.image_handle.capture(url) |
|
61
|
|
|
b64_view_data = base64.b64encode(view_data.dumps()) |
|
62
|
|
|
self.data_control.upload_view_sample( |
|
63
|
|
|
url, |
|
64
|
|
|
view_signature, |
|
65
|
|
|
b64_view_data, |
|
66
|
|
|
) |
|
67
|
|
|
except: |
|
68
|
|
|
error_report = Tools.error_report() |
|
69
|
|
|
raise ViewException("generate._upload", url, error_report) |
|
70
|
|
|
|
|
71
|
|
|
for origin_url in self.data_control.get_urls_from_trustlist(): |
|
72
|
|
|
events.append(_upload(origin_url)) |
|
73
|
|
|
|
|
74
|
|
|
await asyncio.gather(*events) |
|
75
|
|
|
|
|
76
|
|
|
|
|
77
|
|
|
class ViewException(Exception): |
|
78
|
|
|
def __init__(self, cause, url, message): |
|
79
|
|
|
self.err_msg = { |
|
80
|
|
|
"cause": cause, |
|
81
|
|
|
"url": url, |
|
82
|
|
|
"message": message |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
def __str__(self): |
|
86
|
|
|
return "{cause}[{url}]: {message}".format(**self.err_msg) |
|
87
|
|
|
|