Passed
Pull Request — master (#8)
by
unknown
04:37
created

modules.utils   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 150
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 120
dl 0
loc 150
rs 8.96
c 0
b 0
f 0
wmc 43

7 Functions

Rating   Name   Duplication   Size   Complexity  
A extract_url() 0 9 3
B send_image() 0 16 7
B is_image() 0 15 6
C get_image() 0 38 11
A is_image_by_mime_type() 0 9 2
B get_param() 0 22 8
A mp4_fix() 0 9 1

2 Methods

Rating   Name   Duplication   Size   Complexity  
A Caption_Filter.filter() 0 3 4
A Caption_Filter.__init__() 0 2 1

How to fix   Complexity   

Complexity

Complex classes like modules.utils often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
# get_image func courtesy of Slko
4
from telegram.ext import BaseFilter
5
from wand.image import Image
6
import subprocess
7
import requests
8
import os.path
9
import io
10
11
12
def extract_url(entity, text):
13
    if entity["type"] == "text_link":
14
        return entity["url"]
15
    elif entity["type"] == "url":
16
        offset = entity["offset"]
17
        length = entity["length"]
18
        return text[offset:offset+length]
19
    else:
20
        return None
21
22
23
def is_image(path):
24
    if path is None:
25
        return False
26
    ext = None
27
    image_extensions = (".jpg", ".jpeg", ".png", ".gif", ".svg", ".tif", ".bmp", ".mp4")
28
    if path is None:
29
        return False
30
    for i in image_extensions:
31
        if path.casefold().endswith(i):
32
            ext = i
33
            return ext
34
    if ext == None:
35
        ext = ".mp4"
36
        return ext
37
    return False
38
39
def is_image_by_mime_type(mime_type):
40
    if mime_type is None:
41
        return False
42
    mime_types = {
43
        "image/png": ".png",
44
        "image/jpg": ".jpg",
45
        "video/mp4": ".mp4",
46
    }
47
    return mime_types.get(mime_type.casefold(), False)
48
49
50
def get_image(update, context, dl_path, filename):
51
    output = os.path.join(dl_path, filename)
52
    reply = update.message.reply_to_message
53
    if reply is None:
54
        extension = ".jpg"
55
        context.bot.getFile(update.message.photo[-1].file_id).download(output + extension)
56
        return extension
57
    # Entities; url, text_link
58
    if reply.entities is not None:
59
        urls = (extract_url(x, reply.text) for x in reply.entities)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable x does not seem to be defined.
Loading history...
60
        images = [x for x in urls if is_image(x)]
61
        if len(images) > 0:
62
            extension = is_image(images[0])
63
            r = requests.get(images[0])  # use only first image url
64
            with open(output+extension, "wb") as f:
65
                f.write(r.content)
66
            return extension
67
    # Document with file name
68
    if reply.document is not None and is_image(reply.document.file_name):
69
        extension = is_image(reply.document.file_name)
70
        context.bot.getFile(reply.document.file_id).download(output + extension)
71
        return extension
72
    # Document without file name
73
    if reply.document is not None and is_image_by_mime_type(reply.document.mime_type):
74
        extension = is_image_by_mime_type(reply.document.mime_type)
75
        context.bot.getFile(reply.document.file_id).download(output + extension)
76
        return extension
77
    # Sticker
78
    if reply.sticker is not None:
79
        extension = ".webp"
80
        context.bot.getFile(reply.sticker.file_id).download(output+extension)
81
        return extension
82
    # Photo in reply
83
    if reply.photo is not None:
84
        extension = ".jpg"
85
        context.bot.getFile(reply.photo[-1].file_id).download(output + extension)
86
        return extension
87
    return False
88
89
90
def send_image(update, filepath, name, extension):
91
    photo_extensions = (".jpg", ".jpeg")
92
    doc_extensions = (".png", ".svg", ".tif", ".bmp", ".gif", ".mp4")
93
    sticker_extensions = (".webp")
94
    if extension in photo_extensions:
95
        with open(filepath + name + extension, "rb") as f:
96
            update.message.reply_photo(f)
97
        return True  
98
    if extension in doc_extensions:
99
        with open(filepath + name + extension, "rb") as f:
100
            update.message.reply_document(f, timeout=90)
101
        return True
102
    if extension in sticker_extensions:
103
        with open(filepath + name + extension, "rb") as f:
104
            update.message.reply_sticker(f)
105
        return True
106
107
108
def get_param(update, defaultvalue, min_value, max_value):
109
    if update.message.reply_to_message is not None:
110
        parts = update.message.text.split(" ", 1)
111
    elif update.message.caption is not None:
112
        parts = update.message.caption.split(" ", 1)
113
    elif update.message.text is not None:
114
        parts = update.message.text.split(" ", 2)
115
    else:
116
        return defaultvalue
117
    if len(parts) == 1:
118
        parameter = defaultvalue
119
    else:
120
        try:
121
            parameter = int(parts[1])
122
        except:
123
            #update.message.reply_text("Paremeter needs to be a number!")
124
            return defaultvalue
125
        if  parameter < min_value or parameter > max_value:
126
            errtext = "Baka, make it from " + str(min_value) + " to " + str(max_value) + "!"
127
            update.message.reply_text(errtext)
128
            return None
129
    return parameter
130
    
131
def mp4_fix(path, filename):
132
    args = "ffmpeg -loglevel panic -i " + path + filename + ".mp4" + \
133
            " -an -vf scale=trunc(iw/2)*2:trunc(ih/2)*2 \
134
            -pix_fmt yuv420p -c:v libx264 -profile:v high -level:v 2.0 " \
135
            + path + filename + "fixed.mp4 -y"
136
    subprocess.run(args, shell=True)
137
    os.remove(path+filename+".mp4")
138
    fixed_file_name = filename + "fixed"
139
    return fixed_file_name
140
141
142
# custom filters for message handler
143
# photo with caption
144
class Caption_Filter(BaseFilter):
145
    def __init__(self, command):
146
        self.data=command
147
    def filter(self, message):
148
        if message.photo and message.caption and message.caption.startswith(self.data):
149
            return True
150