cache_download()   B
last analyzed

Complexity

Conditions 6

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
c 0
b 0
f 0
dl 0
loc 19
rs 8.5166
1
#    Copyright 2017 Starbot Discord Project
2
# 
3
#    Licensed under the Apache License, Version 2.0 (the "License");
4
#    you may not use this file except in compliance with the License.
5
#    You may obtain a copy of the License at
6
# 
7
#        http://www.apache.org/licenses/LICENSE-2.0
8
# 
9
#    Unless required by applicable law or agreed to in writing, software
10
#    distributed under the License is distributed on an "AS IS" BASIS,
11
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
#    See the License for the specific language governing permissions and
13
#    limitations under the License.
14
15
import inspect
16
import os
17
import urllib.request
18
import urllib.error
19
import urllib
20
import ssl
21
22
from api import database
23
from api.database.table import Table, TableTypes
24
25
def caller_get():
26
    '''Get the caller of the parent function.'''
27
    frm = inspect.stack()[2]
28
    mod = inspect.getmodule(frm[0])
29
    temp = mod.__name__
30
    return temp.split('.')[-1]
31
32
#=============================
33
34
def json_store(string, plugin, filename):
35
    '''Store a json in the database.'''
36
    database.init()
37
    table_strcache = Table('strcache', TableTypes.pGlobal)
38
    filename = '{}_{}'.format(plugin, filename)
39
    try:
40
        entry_strcache = Table.search(table_strcache, 'filename', filename)
41
    except:
42
        # Table must be empty.
43
        entry_strcache = None
44
    if entry_strcache:
45
        entry_strcache.edit(dict(filename=filename, text=string))
46
    else:
47
        Table.insert(table_strcache, dict(filename=filename, text=string))
48
49
50
def json_get(url, caller='', name_custom='', save=True):
51
    '''Retrieve and cache a JSON.'''
52
    if caller == '':
53
        caller_get()
54
    if name_custom == '':
55
        name_custom = url.split('/')[-1]
56
    filename = '{}_{}'.format(caller, name_custom)
57
    # Get cached String
58
    database.init()
59
    table_strcache = Table('strcache', TableTypes.pGlobal)
60
    try:
61
        entry_strcache = Table.search(table_strcache, 'filename', filename)
62
        json_string = entry_strcache.data[2]
63
    except:
64
        json_string = urllib.request.urlopen(urllib.request.Request(url)).read().decode("utf-8")
65
        if save:
66
            json_store(json_string, caller, name_custom)
67
    return json_string
68
69
70
def cache_download(url, filename, caller='', ssl_enabled=True):
71
    '''Download a file to the cache'''
72
    if caller == '':
73
        caller_get()
74
    filename_full = 'cache/{}_{}'.format(caller, filename)
75
    if os.path.isfile(filename_full):
76
        return 1
77
    else:
78
        try:
79
            if ssl_enabled:
80
                urllib.request.urlretrieve(url, filename_full)
81
            else:
82
                ssl._create_default_https_context = ssl._create_unverified_context
83
                urllib.request.urlretrieve(url, filename_full)
84
            return 1
85
        except urllib.error.HTTPError:
86
            return -1
87
        except urllib.error.URLError:
88
            return -2
89