Completed
Push — master ( bbe9e4...65db22 )
by Sepand
01:06
created

error_finder()   C

Complexity

Conditions 7

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
cc 7
c 3
b 1
f 1
dl 0
loc 24
rs 5.5
1
import os
2
import shutil  # Library For Work With File In High Level Like Copy
3
import datetime  # For Adding System Time To Homepage
4
import webbrowser
5
from params import *
6
import socket
7
import requests
8
import re
9
meta_input=""
10
11
def create_folder():  # This Function Create Empty Folder At Begin
12
    folder_flag = 0
13
    list_of_folders = os.listdir(work_dir)
14
    if "doc" not in list_of_folders:
15
        os.mkdir("doc")
16
        file = open(os.path.join(doc_dir, "index.txt"), "w")
17
        file.write("This is For First Page . . .")
18
        file.close()
19
        folder_flag += 1
20
    if "image" not in list_of_folders:
21
        os.mkdir("image")
22
        folder_flag += 1
23
    if "output" not in list_of_folders:
24
        os.mkdir("output")
25
        folder_flag += 1
26
    if "font" not in list_of_folders:
27
        os.mkdir("font")
28
        folder_flag += 1
29
    if folder_flag > 0:
30
        return True
31
    else:
32
        return False
33
34
35
def page_name_update():  # This Function Update Page Names
36
    for i in os.listdir(doc_dir):
37
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
38
            actual_name.append(i[:-4])
39
            page_name.append(i[:-4])
40
41
42
def menu_maker():  # Top Menu Maker In each html page
43
    result = "<center>"
44
    for i in range(len(page_name)):
45
        if page_name[i] == "Home":
46
            targets_blank = ""
47
        else:
48
            targets_blank = 'target="blank"'
49
        result = result + '\t<a href="' + actual_name[i] + '.html"' + targets_blank + '>' + page_name[
50
            i] + "</a>\n"  # Hyper Link To Each Page In HTML File
51
        result += "&nbsp\n"
52
    result += "</center>"
53
    result = result + "\t\t" + break_line  # Add Break line to End Of The Menu
54
    return result  # Return All Of The Menu
55
56
57
def menu_writer():  # Write menu_maker output in html file
58
    message = menu_maker()
59
    for i in range(len(page_name)):
60
        file = open(os.path.join(out_dir, actual_name[i] + ".html"), "a")
61
        file.write(message)
62
        file.close()
63
64
65
def print_meta():
66
    global meta_input
67
    meta_input = input("Please Enter Your Name : ")
68
    static_meta = '<meta name="description" content="Welcome to homepage of ' + meta_input + '"/>\n'
69
    static_meta=static_meta+'<meta property="og:title" content="'+meta_input+'"/>\n'
70
    static_meta=static_meta+'<meta property="og:site_name" content="'+meta_input+'"/>\n'
71
    static_meta=static_meta+'<meta property="og:image" content="favicon.ico" />\n'
72
    if len(meta_input) < 4:
73
        warnings.append("[Warning] Your input for name is too short!!")
74
    return static_meta
75
76
77
def html_init(name):  # Create Initial Form Of each Html Page Like Title And HTML  And Body Tag
78
    html_name = os.path.join(out_dir, name + ".html")
79
    file = open(html_name, "w")
80
    file.write("<html>\n")
81
    file.write("\t<head>\n")
82
    if name == "index":
83
        file.write("\t\t<title>Welcome To My Homepage</title>\n")
84
    else:
85
        file.write("\t\t<title>" + name.upper() + "</title>\n")
86
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
87
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
88
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
89
90
    if name == 'index':  # Add meta only for index page
91
        file.write(print_meta())
92
93
    file.write("\t</head>\n")
94
    file.write('\t<body class="body_tag">\n')
95
    file.close()
96
97
98
def html_end(name):  # Create End Of The Html file
99
    html_name = os.path.join(out_dir, name + ".html")
100
    file = open(html_name, "a")
101
    file.write("\t</body>\n")
102
    file.write("</html>")
103
    file.close()
104
105
106
def close_files():
107
    for i in files:
108
        i.close()
109
110
111
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
112
    text_code = ""
113
    header_start = '<h4 class="color_tag">'
114
    header_end = "</h4>"
115
    space = "&nbsp\n"
116
    for line in text_file:
117
        #header_start = '<h4 class="color_tag">'
118
        #header_end = "</h4>"
119
        line.strip()
120
        text = line
121
        if len(line) == 1:  # For Detecting White Space
122
            text_code = space
123
        else:  # Detecting Font Size
124
            if line.find("[L]") != -1:
125
                header_start = '<h2 class="color_tag">'
126
                header_end = "</h2>"
127
                text = line[3:]
128
            elif line.find("[S]") != -1:
129
                header_start = '<h5 class="color_tag">'
130
                header_end = "</h5>"
131
                text = line[3:]
132
            elif line.find("[M]") != -1:
133
                text = line[3:]
134
        if center:  # Centerizes Text If Condition Is True For Manual Centering
135
            header_start = "<center>" + header_start
136
            header_end += "</center>"
137
        if text.find("[center]") != -1:  # Find Center Tag In Each Line
138
            header_start = "<center>" + header_start
139
            header_end += "</center>"
140
            text = text[:text.find("[center]")]
141
        text_code = header_start + text + header_end + "\n"
142
        file.write(text_code)
143
    if close:
144
        file.close()
145
146
147
def print_image(file, close=False, imformat="jpg"):  # Write Image Part OF The Page
148
    for i in range(len(size_box)):
149
        print(i, "-", size_box[i])
150
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
151
    image_size_string = size_box[2]  # Getting Html String From size_box list default mode (Medium)
152
    if 0 <= image_size < len(size_box):
153
        image_size_string = size_box[image_size]
154
    image_code = '<center><img src="image.' + imformat + '"' + ', width=' + image_size_string + '></img></center>\n'
155
    file.write(image_code)
156
    if close:
157
        file.close()
158
159
160
def print_download(file, name, link, center=False, close=False):  # Create Download Link In Page
161
    link_code = "<a href=" + '"' + link + '"' + target_blank + '>' + name + "</a>"
162
    if center:
163
        link_code = "<center>" + link_code + "</center>"
164
    file.write(link_code + "\n")
165
    file.write(break_line)
166
    if close:
167
        file.close()
168
169
170
def print_adv(file, close=True):
171
    file.write(break_line)
172
    file.write(
173
        '<center><a href=' + '"' + homepage + '"' + target_blank + '>' + "Generated " + today_time + " By" + "QPage " + version + "</a> </center>")
174
    if close:
175
        file.close()
176
177
178
def contain(name):  # main function That Open Each Page HTML File and call other function to write data in it
179
    file = open(os.path.join(out_dir, name + ".html"), "a")
180
    text_file = open(os.path.join(doc_dir, name + ".txt"), "r")
181
    files.append(file)
182
    files.append(text_file)
183
    resume_name = ""
184
    image_name = ""
185
    imformat = "jpg"
186
    if name == "index":
187
        file_of_images = os.listdir(image_dir)
188
        for i in range(len(file_of_images)):
189
            for form in imformat_box:
190
                if file_of_images[i].find("." + form) != -1:
191
                    image_name = os.path.join(image_dir, file_of_images[i])
192
                    imformat = form
193
                    global image_counter
194
                    image_counter=1
195
                    break
196
        shutil.copyfile(image_name, os.path.join(out_dir, "image." + imformat))
197
        print_image(file, imformat=imformat)
198
        print_text(text_file, file)
199
        print_adv(file)
200
    elif name == "Resume":
201
        file_of_docs = os.listdir(doc_dir)
202
        for i in range(len(file_of_docs)):
203
            if file_of_docs[i].find(".pdf") != -1:
204
                resume_name = os.path.join(doc_dir, file_of_docs[i])
205
                break
206
        shutil.copyfile(resume_name, os.path.join(out_dir, "Resume.pdf"))
207
        print_download(file, "Download Full Version", "Resume.pdf", center=True)
208
        print_text(text_file, file)
209
        # print_adv(file)
210
    else:
211
        print_text(text_file, file)
212
        # print_adv(file)
213
214
215
def clear_folder(path):  # This Function Get Path Of Foldr And Delte Its Contains
216
    if os.path.exists(path):
217
        list_of_files = os.listdir(path)
218
        for file in list_of_files:
219
            os.remove(os.path.join(path, file))
220
    else:
221
        os.mkdir(path)
222
223
224
def print_warning():
225
    print(str(len(warnings)) + " Warning , 0 Error")
226
    for i in range(len(warnings)):
227
        print(str(i + 1) + "-" + warnings[i])
228
229
def css_init():
230
    for i in range(len(color_box)):
231
        print(i, "-", color_box[i])
232
    back_color_code = int(input("Please enter your background color : "))
233
    if back_color_code not in range(7):
234
        back_color_code = 0
235
    text_color_code = int(input("Please enter your text color : "))
236
    if text_color_code not in range(7):
237
        text_color_code = 1
238
    if text_color_code == back_color_code:
239
        warnings.append("[Warning] Your text color and background color are same!!")
240
    background_color = color_box[back_color_code]  # convert code to color string in color_box
241
    text_color = color_box[text_color_code]  # convert code to color string in color_box
242
    return [background_color,text_color]
243
244
def css_creator():  # Ask For background and text color in
245
    font_flag = 0  # 0 If there is no font file in font_folder
246
    font_section = 'font-family : Georgia , serif;\n'
247
    colors=css_init()
248
    background_color=colors[0]
249
    text_color=colors[1]
250
    font_folder = os.listdir(font_dir)
251
    for i in font_folder:
252
        for j in range(len(font_format)):  # search for other font format in font box
253
            if i.lower().find(font_format[j]) != -1:  # If there is a font in font folder
254
                shutil.copyfile(os.path.join(font_dir, i),
255
                                os.path.join(out_dir, "qpage" + font_format[j]))  # copy font file to output folder
256
                font_flag = 1  # Turn Flag On
257
                current_font_format = font_format[j]  # font format of current selected font for css editing
258
    css_file = open(os.path.join(out_dir, "styles.css"), "w")  # open css file
259
    if font_flag == 1:  # check flag if it is 1
260
        css_file.write(
261
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage" + current_font_format + ");\n}\n")  # wrtie font-face in html
262
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
263
        for i in range(len(fontstyle_box)):
264
            print(i, "-", fontstyle_box[i])
265
        font_style = int(input(" Please choose your font style "))
266
        if font_style < len(fontstyle_box):
267
            font_style = fontstyle_box[font_style]
268
        else:
269
            font_style = "normal"
270
        font_section = font_section + "font-style:" + font_style + ";\n"
271
    css_file.write(
272
        ".body_tag{\n" + "background-color:" + background_color + ";\n" + font_section + css_margin +css_animation_1+ "}\n")  # write body tag
273
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
274
    css_file.write(css_animation_2)
275
    css_file.close()  # close css file
276
277
278
def preview():
279
    webbrowser.open(os.path.join(out_dir, "index.html"))
280
281
282
def error_finder():
283
    error_vector = []
284
    pass_vector = []
285
    pdf_counter = 0
286
    if image_counter == 1:
287
        pass_vector.append("[Pass] Your profile image in OK!!")
288
    else:
289
        error_vector.append("[Error] Your profile image is not in correct format")
290
    if len(doc_list) == 0:
291
        error_vector.append("[Error] There is no file in doc folder ( index.txt and .pdf file in necessary)")
292
    else:
293
        if "index.txt" in doc_list:
294
            pass_vector.append("[Pass] index.txt file OK!")
295
        else:
296
            error_vector.append("[Error] index.txt is not in doc folder!")
297
        for j in doc_list:
298
            if j.find(".pdf") != -1:
299
                pdf_counter = 1
300
                break
301
        if pdf_counter == 0:
302
            error_vector.append("[Error] Where Is Your Resume File? It should be in doc folder")
303
        else:
304
            pass_vector.append("[Pass] Your Resume File is OK!!")
305
    return [error_vector, pass_vector]
306
307
308
def icon_creator():
309
    icon_flag=0
310
    for file in os.listdir(image_dir):
311
        if file.endswith('ico'):
312
            shutil.copy(os.path.join(image_dir, file), out_dir)
313
            os.rename(os.path.join(out_dir, file), os.path.join(out_dir, 'favicon.ico'))
314
            icon_flag=1
315
            break
316
    if "favicon.ico" in os.listdir(work_dir) and icon_flag==0:
317
        shutil.copy(os.path.join(work_dir, "favicon.ico"), out_dir)
318
        warnings.append("[warning] There is no icon for this website")
319
def robot_maker(): # This Function Create Robots.txt for pages
320
    robots=open(os.path.join(out_dir,"robots.txt"),"w")
321
    robots.write("User-agent: *\n")
322
    robots.write("Disallow: ")
323
    robots.close()
324
def internet(host="8.8.8.8", port=53, timeout=3):
325
    try:
326
        socket.setdefaulttimeout(timeout)
327
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
328
        return True
329
    except Exception as ex:
330
        return False
331
def server():
332
    global meta_input
333
    url="http://sepkjaer.pythonanywhere.com/install"
334
    headers = {'content-type': 'application/json',"NAME":meta_input,"Version":"3"}
335
    response=requests.get(url,headers=headers)
336
    #print(response)
337
def version_control():
338
    try:
339
        version_pattern=r"last_version:(.+)"
340
        if internet():
341
            response=requests.get("http://www.qpage.ir/releases.html")
342
            body=response.text
343
            last_version=float(re.findall(version_pattern,body)[0][:-3])
344
            if last_version>float(version):
345
                print("--------------------------------------------------------------------------")
346
                print("**New Version Of Qpage Is Available Now (Version "+str(last_version)+")**")
347
                print("Download Link -->"+"https://github.com/sepandhaghighi/qpage/archive/v"+str(last_version)+".zip")
348
                print("--------------------------------------------------------------------------")
349
    except:
350
        pass
351
def enter_to_exit():
352
    input("Enter any key to exit()")
353
354