Completed
Push — master ( d56cef...506b82 )
by Sepand
51s
created

build_resume()   A

Complexity

Conditions 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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