Completed
Push — master ( 047272...d56cef )
by Sepand
48s
created

generation_time()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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