Completed
Push — master ( 9b5cfc...648d41 )
by Mohammad Mahdi
56s
created

css_creator()   A

Complexity

Conditions 1

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 14
Bugs 5 Features 7
Metric Value
cc 1
c 14
b 5
f 7
dl 0
loc 22
rs 9.2
1
import shutil  # Library For Work With File In High Level Like Copy
2
import webbrowser
3
from params import *
4
import socket
5
import requests
6
import re
7
import time
8
import sys
9
import urllib.request
10
11
meta_input = ""
12
13
14
def create_badge(subject="qpage", status=version, color="blue"):
15
    if color not in badge_color_list:
16
        color = "orange"
17
    return adv_badge_static + subject + "-" + status + "-" + color + '.svg'
18
19
20
def is_sample_downloaded():
21
    download_list = []
22
    if "profile.png" not in os.listdir(image_dir):
23
        download_list.append(0)
24
    if "font.TTF" not in os.listdir(font_dir):
25
        download_list.append(1)
26
    if "resume.pdf" not in os.listdir(doc_dir) and "resume.txt" not in os.listdir(doc_dir):
27
        download_list.extend([2, 3])
28
    if "icon.ico" not in os.listdir(image_dir):
29
        download_list.append(4)
30
    return download_list
31
32
33
def download_lorem():
34
    if internet():
35
        urllib.request.urlretrieve("http://www.qpage.ir/sample/Latin-Lipsum.txt", "Latin-Lipsum.txt")
36
    else:
37
        print("Error In Download Lorem")
38
39
40
def read_lorem(char=100):
41
    try:
42
        if "Latin-Lipsum.txt" not in os.listdir(work_dir):
43
            download_lorem()
44
        lorem_file = open("Latin-Lipsum.txt", "r")
45
        lorem_text = lorem_file.read()
46
        lorem_file.close()
47
        return " ".join(lorem_text.split(" ")[:char])
48
    except:
49
        return None
50
51
52
def sample_site_download(item_list):
53
    try:
54
        if internet():
55
            for i in item_list:
56
                print("Downloading " + sample_dict_message[i] + " . . . [" + str(i + 1) + "/4]")
57
                print_line(70)
58
                urllib.request.urlretrieve(list(sample_dict_addr.values())[i],
59
                                           os.path.join(image_dir, list(sample_dict_addr.keys())[i]))
60
            print("Done! All Material Downloaded")
61
            print_line(70)
62
        else:
63
            print("Error In Internet Connection!")
64
            print_line(70)
65
    except:
66
        print("Error in downloading sample files check your internet conection")
67
        print_line(70)
68
69
70
def logger(status=False):
71
    file = open("build_log.txt", "a")
72
    if status == False:
73
        file.write("Faild  " + str(datetime.datetime.now()) + "\n")
74
    else:
75
        file.write("Sucess " + str(datetime.datetime.now()) + "\n")
76
    file.close()
77
78
79
def print_line(number, char="-"):
80
    line = ""
81
    for i in range(number):
82
        line = line + char
83
    print(line)
84
85
86
def name_standard(name):
87
    reponse_name = name[0].upper() + name[1:].lower()
88
    return reponse_name
89
90
91
def address_print():
92
    print_line(70, "*")
93
    print("Where--> " + work_dir)
94
    print_line(70, "*")
95
96
97
def create_folder():  # This Function Create Empty Folder At Begin
98
    folder_flag = 0
99
    list_of_folders = os.listdir(work_dir)
100
    for i in ["doc", "image", "output", "font"]:
101
        if i not in list_of_folders:
102
            os.mkdir(i)
103
            folder_flag += 1
104
            if i == "doc":
105
                file = open(os.path.join(doc_dir, "index.txt"), "w")
106
                if read_lorem() == None:
107
                    file.write("This is For First Page . . .")
108
                else:
109
                    file.write(read_lorem())
110
                file.close()
111
    return bool(folder_flag)
112
113
114
def page_name_update():  # This Function Update Page Names
115
    for i in os.listdir(doc_dir):
116
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
117
            actual_name.append(i[:-4])
118
            page_name.append(i[:-4])
119
120
121
def menu_maker():  # Top Menu Maker In each html page
122
    result = "<center>"
123
    for i in range(len(page_name)):
124
        if page_name[i] == "Home":
125
            targets_blank = ""
126
        else:
127
            targets_blank = 'target="blank"'
128
        result = result + '\t<a href="' + actual_name[i] + '.html"' + targets_blank + '>' + name_standard(page_name[
129
                                                                                                              i]) + "</a>\n"  # Hyper Link To Each Page In HTML File
130
        result += "&nbsp\n"
131
    result += "</center>"
132
    result = result + "\t\t" + break_line  # Add Break line to End Of The Menu
133
    return result  # Return All Of The Menu
134
135
136
def menu_writer():  # Write menu_maker output in html file
137
    message = menu_maker()
138
    for i in range(len(page_name)):
139
        file = open(os.path.join(out_dir, actual_name[i] + ".html"), "a")
140
        file.write(message)
141
        file.close()
142
143
144
def print_meta():
145
    global meta_input
146
    meta_input = input("Please Enter Your Name : ")
147
    static_meta = '<meta name="description" content="Welcome to homepage of ' + meta_input + '"/>\n'
148
    static_meta = static_meta + '<meta property="og:title" content="' + meta_input + '"/>\n'
149
    static_meta = static_meta + '<meta property="og:site_name" content="' + meta_input + '"/>\n'
150
    static_meta = static_meta + '<meta property="og:image" content="favicon.ico" />\n'
151
    if len(meta_input) < 4:
152
        warnings.append("[Warning] Your input for name is too short!!")
153
    return static_meta
154
155
156
def html_init(name):  # Create Initial Form Of each Html Page Like Title And HTML  And Body Tag
157
    html_name = os.path.join(out_dir, name + ".html")
158
    file = open(html_name, "w")
159
    file.write("<html>\n")
160
    file.write("\t<head>\n")
161
    if name == "index":
162
        file.write("\t\t<title>Welcome To My Homepage</title>\n")
163
    else:
164
        file.write("\t\t<title>" + name_standard(name) + "</title>\n")
165
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
166
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
167
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
168
169
    if name == 'index':  # Add meta only for index page
170
        file.write(print_meta())
171
172
    file.write("\t</head>\n")
173
    file.write('\t<body class="body_tag">\n')
174
    file.close()
175
176
177
def html_end(name):  # Create End Of The Html file
178
    html_name = os.path.join(out_dir, name + ".html")
179
    file = open(html_name, "a")
180
    file.write("\t</body>\n")
181
    file.write("</html>")
182
    file.close()
183
184
185
def close_files():
186
    for i in files:
187
        i.close()
188
189
190
def LSM_translate(line, center):
191
    line.strip()
192
    text = line
193
    header_start = '<h4 class="color_tag">'
194
    header_end = "</h4>"
195
    if line.find("[L]") != -1:
196
        header_start = '<h2 class="color_tag">'
197
        header_end = "</h2>"
198
        text = line[3:]
199
    elif line.find("[S]") != -1:
200
        header_start = '<h5 class="color_tag">'
201
        header_end = "</h5>"
202
        text = line[3:]
203
    elif line.find("[M]") != -1:
204
        text = line[3:]
205
    if center:  # Centerizes Text If Condition Is True For Manual Centering
206
        header_start = "<center>" + header_start
207
        header_end += "</center>"
208
    if text.find("[center]") != -1:  # Find Center Tag In Each Line
209
        header_start = "<center>" + header_start
210
        header_end += "</center>"
211
        text = text[:text.find("[center]")]
212
    return [text, header_end, header_start]
213
214
215
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
216
    text_code = ""
217
    for line in text_file:
218
        if len(line) == 1:
219
            text_code = space
220
        else:
221
            text_header = LSM_translate(line, center)
222
            text = text_header[0]
223
            header_end = text_header[1]
224
            header_start = text_header[2]
225
            text_code = header_start + text + header_end + "\n"
226
        file.write(text_code)
227
    if close:
228
        file.close()
229
230
231
def print_image(file, close=False, image_format="jpg"):  # Write Image Part OF The Page
232
    for i in range(len(size_box)):
233
        print(i, "-", size_box[i])
234
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
235
    image_size_string = size_box[2]  # Getting Html String From size_box list default mode (Medium)
236
    if 0 <= image_size < len(size_box):
237
        image_size_string = size_box[image_size]
238
    image_code = '<center><img src="image.' + image_format + '"' + ', width=' + image_size_string + ' alt="profile image"></img></center>\n'
239
    file.write(image_code)
240
    if close:
241
        file.close()
242
243
244
def print_download(file, name, link, center=False, close=False):  # Create Download Link In Page
245
    link_code = "<a href=" + '"' + link + '"' + target_blank + '>' + name + "</a>"
246
    if center:
247
        link_code = "<center>" + link_code + "</center>"
248
    file.write(link_code + "\n")
249
    file.write(break_line)
250
    if close:
251
        file.close()
252
253
254
def print_adv(file, close=True):
255
    file.write(break_line)
256
    file.write(
257
        '<center>' + "<p>" + "Generated " + today_time + " By" + "</p>" + '<a href=' + '"' + homepage + '"' + target_blank + '>' + '<img src="' + create_badge() + '"</a> </center>')
258
    if close:
259
        file.close()
260
261
262 View Code Duplication
def build_index(file):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
263
    image_name = ""
264
    img_format = "jpg"
265
    file_of_images = os.listdir(image_dir)
266
    for i in range(len(file_of_images)):
267
        for form in imformat_box:
268
            if file_of_images[i].find("." + form) != -1:
269
                image_name = os.path.join(image_dir, file_of_images[i])
270
                img_format = form
271
                global image_counter
272
                image_counter = 1
273
                break
274
    shutil.copyfile(image_name, os.path.join(out_dir, "image." + img_format))
275
    print_image(file, image_format=img_format)
276
277
278
def build_resume(file):
279
    resume_name = ""
280 View Code Duplication
    file_of_docs = os.listdir(doc_dir)
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
281
    for i in range(len(file_of_docs)):
282
        if file_of_docs[i].find(".pdf") != -1:
283
            resume_name = os.path.join(doc_dir, file_of_docs[i])
284
            global pdf_counter
285
            pdf_counter = 1
286
            break
287
    shutil.copyfile(resume_name, os.path.join(out_dir, "Resume.pdf"))
288
    print_download(file, "Download Full Version", "Resume.pdf", center=True)
289
290
291
def contain(name):  # main function That Open Each Page HTML File and call other function to write data in it
292
    file = open(os.path.join(out_dir, name + ".html"), "a")
293
    text_file = open(os.path.join(doc_dir, name + ".txt"), "r")
294
    files.append(file)
295
    files.append(text_file)
296
297
    if name.upper() == "INDEX":
298
        build_index(file)
299
    elif name.upper() == "RESUME":
300
        build_resume(file)
301
302
    print_text(text_file, file)
303
    print_adv(file)
304
305
306
def clear_folder(path):  # This Function Get Path Of Foldr And Delte Its Contains
307
    if os.path.exists(path):
308
        list_of_files = os.listdir(path)
309
        for file in list_of_files:
310
            os.remove(os.path.join(path, file))
311
    else:
312
        os.mkdir(path)
313
314
315
def print_warning():
316
    print(str(len(warnings)) + " Warning , 0 Error")
317
    for i in range(len(warnings)):
318
        print(str(i + 1) + "-" + warnings[i])
319
320
321
def get_color_code():
322
    for i in range(len(color_box)):
323
        print(i, "-", color_box[i])
324
    back_color_code = int(input("Please enter your background color : "))
325
    if back_color_code not in range(7):
326
        back_color_code = 0
327
    text_color_code = int(input("Please enter your text color : "))
328
    if text_color_code not in range(7):
329
        text_color_code = 1
330
    return [back_color_code, text_color_code]
331
332
333
def color_code_map():
334
    [back_color_code, text_color_code] = get_color_code()
335
    if text_color_code == back_color_code:
336
        warnings.append("[Warning] Your text color and background color are same!!")
337
    background_color = color_box[back_color_code]  # convert code to color string in color_box
338
    text_color = color_box[text_color_code]  # convert code to color string in color_box
339
    return [background_color, text_color]
340
341
342
def css_font(font_folder):
343
    font_flag = 0  # 0 If there is no font file in font_folder
344
    current_font_format = None
345
    for i in font_folder:
346
        for j in range(len(font_format)):  # search for other font format in font box
347
            if i.lower().find(font_format[j]) != -1:  # If there is a font in font folder
348
                shutil.copyfile(os.path.join(font_dir, i),
349
                                os.path.join(out_dir, "qpage" + font_format[j]))  # copy font file to output folder
350
                font_flag = 1  # Turn Flag On
351
                current_font_format = font_format[j]  # font format of current selected font for css editing
352
    return [font_flag, current_font_format]
353
354
355
def font_creator(css_file, font_section):
356
357
    font_folder = os.listdir(font_dir)
358
    details = css_font(font_folder)
359
    current_font_format = details[1]
360
    font_flag = details[0]
361
362
    if font_flag == 1:  # check flag if it is 1
363
        css_file.write(
364
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage"
365
            + current_font_format
366
            + ");\n}\n")  # Write font-face in html
367
368
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
369
        for i in range(len(fontstyle_box)):
370
            print(i, "-", fontstyle_box[i])
371
        font_style = int(input(" Please choose your font style "))
372
        if font_style < len(fontstyle_box):
373
            font_style = fontstyle_box[font_style]
374
        else:
375
            font_style = "normal"
376
        font_section = font_section + "font-style:" + font_style + ";\n"
377
    else:
378
        warnings.append("[Warning] There is no specific font set for this website!!")
379
    return font_section
380
381
382
def css_creator():  # Ask For background and text color in
383
    font_section = 'font-family : Georgia , serif;\n'
384
    colors = color_code_map()
385
    background_color = colors[0]
386
    text_color = colors[1]
387
388
    css_file = open(os.path.join(out_dir, "styles.css"), "w")  # open css file
389
    font_section = font_creator(css_file, font_section)
390
391
    css_file.write(
392
        ".body_tag{\n"
393
        + "background-color:"
394
        + background_color
395
        + ";\n"
396
        + font_section
397
        + css_margin
398
        + css_animation_1
399
        + "}\n")  # write body tag
400
401
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
402
    css_file.write(css_animation_2)
403
    css_file.close()  # close css file
404
405
406
def preview():
407
    webbrowser.open(os.path.join(out_dir, "index.html"))
408
409
410
def error_finder():
411
    error_vector = []
412
    pass_vector = []
413
    pdf_counter = 0
414
    image_list = os.listdir(image_dir)
415
    doc_list = os.listdir(doc_dir)
416
    if image_counter == 1:
417
        pass_vector.append("[Pass] Your profile image in OK!!")
418
    else:
419
        error_vector.append("[Error] Your profile image is not in correct format")
420
    if len(doc_list) == 0:
421
        error_vector.append("[Error] There is no file in doc folder ( index.txt and .pdf file in necessary)")
422
    else:
423
        if "index.txt" in doc_list:
424
            pass_vector.append("[Pass] index.txt file OK!")
425
        else:
426
            error_vector.append("[Error] index.txt is not in doc folder!")
427
        if pdf_counter == 0:
428
            error_vector.append("[Error] Where Is Your Resume File? It should be in doc folder")
429
        else:
430
            pass_vector.append("[Pass] Your Resume File is OK!!")
431
    return [error_vector, pass_vector]
432
433
434
def icon_creator():
435
    icon_flag = 0
436
    for file in os.listdir(image_dir):
437
        if file.endswith('ico'):
438
            shutil.copy(os.path.join(image_dir, file), out_dir)
439
            os.rename(os.path.join(out_dir, file), os.path.join(out_dir, 'favicon.ico'))
440
            icon_flag = 1
441
            break
442
    if "favicon.ico" in os.listdir(work_dir) and icon_flag == 0:
443
        shutil.copy(os.path.join(work_dir, "favicon.ico"), out_dir)
444
        warnings.append("[warning] There is no icon for this website")
445
446
447
def robot_maker():  # This Function Create Robots.txt for pages
448
    robots = open(os.path.join(out_dir, "robots.txt"), "w")
449
    robots.write("User-agent: *\n")
450
    robots.write("Disallow: ")
451
    robots.close()
452
453
454
def internet(host="8.8.8.8", port=53, timeout=3):
455
    try:
456
        socket.setdefaulttimeout(timeout)
457
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
458
        return True
459
    except Exception as ex:
460
        return False
461
462
463
def server():
464
    global meta_input
465
    url = "http://sepkjaer.pythonanywhere.com/install"
466
    headers = {'content-type': 'application/json', "NAME": meta_input, "Version": "3"}
467
    response = requests.get(url, headers=headers)
468
    # print(response)
469
470
471
def version_control():
472
    try:
473
        print("Check for new version . . .")
474
        print_line(70)
475
        version_pattern = r"last_version:(.+)"
476
        if internet():
477
            response = requests.get("http://www.qpage.ir/releases.html")
478
            body = response.text
479
            last_version = float(re.findall(version_pattern, body)[0][:-3])
480
            if last_version > float(version):
481
                print_line(70)
482
                print("**New Version Of Qpage Is Available Now (Version " + str(last_version) + ")**")
483
                print("Download Link -->" + "https://github.com/sepandhaghighi/qpage/archive/v" + str(
484
                    last_version) + ".zip")
485
                print_line(70)
486
            else:
487
                print("Already Updated!!!")
488
                print_line(70)
489
    except:
490
        pass
491
492
493
def enter_to_exit(mode=False):
494
    print_line(70, "*")
495
    response = input("Enter [R] for restart Qpage and any other key to exit : ")
496
    if response.upper() != "R":
497
        sys.exit()
498
499
500
def wait_func(iteration):
501
    for i in range(iteration):
502
        time.sleep(1)
503
        print(".")
504