Completed
Push — master ( a56332...df0161 )
by Sepand
01:00
created

print_logo()   B

Complexity

Conditions 5

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 1
Metric Value
cc 5
c 3
b 1
f 1
dl 0
loc 16
rs 8.5454
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
import platform
11
import random
12
import datetime
13
from functools import reduce
14
15
meta_input = ""
16
17
18
def show_items(enum_list):
19
    """ show item of enum_list
20
    :param enum_list the list that should be shown
21
    :type enum_list : list
22
    """
23
    for i, item in enumerate(enum_list):  # print errors
24
        print(str(i + 1) + "-" + item)  # print pass
25
26
27
def print_logo(external=False):
28
    '''
29
    print qpage logo by characters
30
    :param external: bool , choose internal or external logo
31
    :return: None
32
    '''
33
    if external==True:
34
        if "logo.txt" in os.listdir(RESOURCE_DIR):
35
            logo_path = os.path.join(RESOURCE_DIR, 'logo.txt')
36
            with open(logo_path, "r") as logo_file:
37
                for line in logo_file:
38
                    print(line.rstrip())
39
        else:
40
            pass
41
    else:
42
        print(LOGO)
43
44
45
def convert_bytes(num):
46
    """ convert num to idiomatic byte unit
47
48
    :param num: the input number.
49
    """
50
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
51
        if num < 1024.0:
52
            return "%3.1f %s" % (num, x)
53
        num /= 1024.0
54
55
56
def file_size():
57
    """ Print the size of output file
58
59
    """
60
    list_of_files = os.listdir(OUT_DIR)
61
    response = 0
62
    for file in list_of_files:
63
        file_info = os.stat(os.path.join(OUT_DIR, file))
64
        response += file_info.st_size
65
    print_line(70, "*")
66
    print("Used SPACE --> " + convert_bytes(response))
67
    print_line(70, "*")
68
69
70
def download_badge(address):
71
    """ Download badge for website
72
73
    :param address: the address that should get badge
74
    """
75
    r = requests.get(address, stream=True)
76
    with open(os.path.join(OUT_DIR, "badge.svg"), 'wb') as f:
77
        shutil.copyfileobj(r.raw, f)
78
79
80
def random_badge_color():
81
    """return a random color for badge
82
83
    """
84
    random_index = random.randint(0, len(BADGE_COLOR_LIST) - 1)
85
    return BADGE_COLOR_LIST[random_index]
86
87
88
def system_details():
89
    """ Show detail of system that code is runnig on
90
91
    """
92
    return platform.node() + " , " + platform.processor() + " ,  " + platform.platform()
93
94
95
def generation_time(time_1=None):
96
    """ Calculate the generation time
97
98
    :param time_1: time that passed but not counted in generation time
99
    :return :the amount of time that passed .
100
    """
101
    if time_1 is None:
102
        return time.perf_counter()
103
    else:
104
        return time.perf_counter() - time_1
105
106
107
def find_global_ip():
108
    """ Find the ip for use in API
109
110
    :return: return the IP.
111
    """
112
    try:
113
        response = requests.get(IP_FINDER_API)
114
        return response.text[:-1]
115
    except Exception as e:
116
        error_log(e)
117
        return "0.0.0.0"
118
119
120
def create_badge(subject="qpage", status=VERSION, color="blue", random=False):
121
    if random:
122
        color = random_badge_color()
123
    else:
124
        if color not in BADGE_COLOR_LIST:
125
            color = "orange"
126
    badge_adr = ADV_BADGE_STATIC + subject + "-" + status + "-" + color + '.svg'
127
    return badge_adr
128
129
130
def is_sample_downloaded():
131
    """ Check the sample site material is downloaded
132
133
    :return : list of the materials
134
    """
135
    download_list = []
136
    if "profile.png" not in os.listdir(IMAGE_DIR):
137
        download_list.append(0)
138
    if "font.TTF" not in os.listdir(FONT_DIR):
139
        download_list.append(1)
140
    if "resume.pdf" not in os.listdir(DOC_DIR) and "resume.txt" not in os.listdir(DOC_DIR):
141
        download_list.extend([2, 3])
142
    if "icon.ico" not in os.listdir(IMAGE_DIR):
143
        download_list.append(4)
144
    return download_list
145
146
147
def download_lorem():
148
    """ Download the lorem file
149
150
    """
151
    if internet():
152
        lorem_path = os.path.join(RESOURCE_DIR, 'Latin-Lipsum.txt')
153
        urllib.request.urlretrieve("http://www.qpage.ir/sample/Latin-Lipsum.txt", lorem_path)
154
    else:
155
        print("Error In Download Lorem")
156
157
158
def read_lorem(char=100):
159
    """ find and read lorem
160
161
    :param char: the amount of char that needed
162
    :return : the lorme string
163
    """
164
    try:
165
        if "Latin-Lipsum.txt" not in os.listdir(RESOURCE_DIR):
166
            download_lorem()
167
        lorem_path = os.path.join(RESOURCE_DIR, 'Latin-Lipsum.txt')
168
        lorem_file = open(lorem_path, "r")
169
        lorem_text = lorem_file.read()
170
        lorem_file.close()
171
        return " ".join(lorem_text.split(" ")[:char])
172
    except Exception as e:
173
        error_log(e)
174
        return None
175
176
177
def sample_site_download(item_list):
178
    """Download sample material for make a fake site
179
180
    :param item_list: Download items form item_list
181
    """
182
    try:
183
        if internet():
184
            for i in item_list:
185
                print("Downloading " + SAMPLE_DICT_MESSAGE[i] + " . . . [" + str(i + 1) + "/5]")
186
                print_line(70)
187
                urllib.request.urlretrieve(list(SAMPLE_DICT_ADDR.values())[i],
188
                                           os.path.join(IMAGE_DIR, list(SAMPLE_DICT_ADDR.keys())[i]))
189
            print("Done! All Material Downloaded")
190
            print_line(70)
191
        else:
192
            print("Error In Internet Connection!")
193
            print_line(70)
194
    except Exception as e:
195
        error_log(e)
196
        print("Error in downloading sample files check your internet conection")
197
        print_line(70)
198
199
200
def logger(status=False, perf_time=None):
201
    """Show the build log of the app
202
203
    :param status: show status of app.
204
    :param perf_time : show the time passed for generate files
205
    """
206
    if "log" not in os.listdir():
207
        os.mkdir("log")
208
    file = open(reduce(os.path.join, [os.getcwd(), "log", "build_log.txt"]), "a")
209
    if not status:
210
        file.write("Failed  " + str(datetime.datetime.now()) + "\n")
211
    else:
212
        file.write("Success " + str(datetime.datetime.now()) + "\n")
213
        file.write("Generation Time: " + str(perf_time) + "\n")
214
    file.close()
215
216
217
def error_log(msg):
218
    """Show the errorlog of the app
219
220
        :param msg: error message
221
    """
222
    if "log" not in os.listdir():
223
        os.mkdir("log")
224
    file = open(reduce(os.path.join, [os.getcwd(), "log", "error_log.txt"]), "a")
225
    file.write(str(datetime.datetime.now()) + " --> " + str(msg) + "\n")
226
    file.close()
227
228
229
def print_line(number, char="-"):
230
    """ Print a Line
231
232
    :param number: the amount char that in lien
233
    :param char  : the char that used to draw line
234
    """
235
    line = ""
236
    i = 0
237
    while (i < number):
238
        line += char
239
        i += 1
240
    print(line)
241
242
243
def name_standard(name):
244
    """ return the Standard VERSION of the input word
245
246
    :param name: the name that should be standard
247
    :return name: the standard form of word
248
    """
249
    reponse_name = name[0].upper() + name[1:].lower()
250
    return reponse_name
251
252
253
def address_print():
254
    """Print the working directory
255
256
    """
257
    print_line(70, "*")
258
    print("Where --> " + SOURCE_DIR)
259
    print_line(70, "*")
260
261
262
def create_folder():
263
    """This Function Create Empty Folder At Begin
264
265
    """
266
    folder_flag = 0
267
    list_of_folders = os.listdir(SOURCE_DIR)
268
    for i in ["doc", "image", "output", "font"]:
269
        if i not in list_of_folders:
270
            os.mkdir(i)
271
            folder_flag += 1
272
            if i == "doc":
273
                file = open(os.path.join(DOC_DIR, "index.txt"), "w")
274
                if read_lorem() is None:
275
                    file.write("This is For First Page . . .")
276
                else:
277
                    file.write(read_lorem())
278
                file.close()
279
    return bool(folder_flag)
280
281
282
def page_name_update():
283
    """This Function Update Page Names
284
285
    """
286
    for i in os.listdir(DOC_DIR):
287
        if i.find(".txt") != -1 and i[:-4].upper() != "INDEX":
288
            ACTUAL_NAME.append(i[:-4])
289
            PAGE_NAME.append(i[:-4])
290
291
292
def menu_maker():
293
    """Top Menu Maker In each html page
294
295
    """
296
    result = "<center>"
297
    for i, item in enumerate(PAGE_NAME):
298
        if item == "Home":
299
            targets_blank = ""
300
        else:
301
            targets_blank = 'target="blank"'
302
            # Hyper Link To Each Page In HTML File
303
        result += '\t<a href="' \
304
                  + ACTUAL_NAME[i] + '.html"' + targets_blank + '>' + name_standard(item) + "</a>\n"
305
        result += "&nbsp\n"
306
    result += "</center>"
307
    result = result + "\t\t" + BREAK_LINE  # Add Break line to End Of The Menu
308
    return result  # Return All Of The Menu
309
310
311
def menu_writer():  #
312
    """Write menu_maker output in html and close file after
313
314
    """
315
    message = menu_maker()
316
    PAGE_NAME_length = len(PAGE_NAME)
317
    for i in range(PAGE_NAME_length):
318
        file = open(os.path.join(OUT_DIR, ACTUAL_NAME[i] + ".html"), "a")
319
        file.write(message)
320
        file.close()
321
322
323
def print_meta():
324
    """Add meta to html files
325
326
    :return static_meta: The meta that created
327
    """
328
    global meta_input
329
    meta_input = input("Please Enter Your Name : ")
330
    static_meta = '<meta name="description" content="Welcome to HOMEPAGE of ' + meta_input + '"/>\n'
331
    static_meta += '<meta property="og:title" content="' + meta_input + '"/>\n'
332
    static_meta += '<meta property="og:site_name" content="' + meta_input + '"/>\n'
333
    static_meta += '<meta property="og:image" content="favicon.ico" />\n'
334
    if len(meta_input) < 4:
335
        warnings.append("[Warning] Your input for name is too short!!")
336
    return static_meta
337
338
339
def html_init(name):
340
    """Create Initial Form Of each Html Page Like Title And HTML  And Body Tag.
341
342
    :param name: the name of html file.
343
    """
344
345
    html_name = os.path.join(OUT_DIR, name + ".html")
346
    file = open(html_name, "w")
347
    file.write("<html>\n")
348
    file.write("\t<head>\n")
349
    if name == "index":
350
        file.write("\t\t<title>Welcome To My HOMEPAGE</title>\n")
351
    else:
352
        file.write("\t\t<title>" + name_standard(name) + "</title>\n")
353
    file.write('<link rel="stylesheet" href="styles.css" type="text/css"/>\n')
354
    css_link = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css'
355
    file.write('<link rel="stylesheet" href= ' + css_link + ' type="text/style"/>\n')
356
357
    if name == 'index':  # Add meta only for index page
358
        file.write(print_meta())
359
360
    file.write("\t</head>\n")
361
    file.write('\t<body class="body_tag">\n')
362
    file.close()
363
364
365
def html_end(name):
366
    """Create End Of The Html and close file
367
368
    :param name: The name of html file.
369
    """
370
    html_name = os.path.join(OUT_DIR, name + ".html")
371
    file = open(html_name, "a")
372
    file.write("\t</body>\n")
373
    file.write("</html>")
374
    file.close()
375
376
377
def close_files():
378
    """Close all the files.
379
380
    """
381
    for i in files:
382
        if i.closed == False:
383
            i.close()
384
385
386
def LSM_translate(line, center):
387
    # TODO : write a document for this function
388
    """ ????
389
390
    :param line: the input line.
391
    :param center: put it in center
392
393
    :return : return a list contain text header end and header begin
394
    """
395
    line.strip()
396
    text = line
397
    header_start = '<h4 class="color_tag">'
398
    header_end = "</h4>"
399
    if line.find("[L]") != -1:
400
        header_start = '<h2 class="color_tag">'
401
        header_end = "</h2>"
402
        text = line[3:]
403
    elif line.find("[S]") != -1:
404
        header_start = '<h5 class="color_tag">'
405
        header_end = "</h5>"
406
        text = line[3:]
407
    elif line.find("[M]") != -1:
408
        text = line[3:]
409
    if center:  # Centuries Text If Condition Is True For Manual Centering
410
        header_start = "<center>" + header_start
411
        header_end += "</center>"
412
    if text.find("[center]") != -1:  # Find Center Tag In Each Line
413
        header_start = "<center>" + header_start
414
        header_end += "</center>"
415
        text = text[:text.find("[center]")]
416
    return [text, header_end, header_start]
417
418
419
def print_text(text_file, file, center=False, close=False):  # Write Text Part Of Each Page
420
    """Write the text part of each page
421
422
    :param text_file: Text tha should be written.
423
    :param file     : The file that text will be written inside.
424
    :param center   : put the text in center.
425
    :param close    : close file after done editing
426
427
    :type close : bool
428
    :type center: bool
429
430
    """
431
432
    text_code = ""
433
    for line in text_file:
434
        if len(line) == 1:
435
            text_code = SPACE
436
        else:
437
            text_header = LSM_translate(line, center)
438
            text = text_header[0]
439
            header_end = text_header[1]
440
            header_start = text_header[2]
441
            text_code = header_start + text + header_end + "\n"
442
        file.write(text_code)
443
    if close:
444
        file.close()
445
446
447
def print_image(file, image_format="jpg", close=False):
448
    """Write Image Part OF The Page.
449
450
    :param file: The file that images will be added.
451
    :param close : close file after done editing.
452
    :param image_format: the format of image
453
454
    :type close : bool
455
    """
456
    for i, item in enumerate(SIZE_BOX):
457
        print(i, "-", item)
458
    image_size = int(input("Please Enter Profile Image Size : "))  # Choose Profile Image Size
459
    image_size_string = SIZE_BOX[2]  # Getting Html String From SIZE_BOX list default mode (Medium)
460
    if 0 <= image_size < len(SIZE_BOX):
461
        image_size_string = SIZE_BOX[image_size]
462
    image_code = '<center><img src="image.' + image_format + '"' + ', width=' + image_size_string + ' alt="profile image"></img></center>\n'
463
    file.write(image_code)
464
    if close:
465
        file.close()
466
467
468
def print_download(file, name, link, center=False, close=False):
469
    """ Create Download Link in page
470
471
    :param file: The file that contain html of page.
472
    :param name: The name of the link
473
    :param link: The place that name is Linked
474
    :param center: put the text in center
475
    :param close : close file after done editing
476
477
    :type center: bool
478
    :type close : bool
479
480
    """
481
    link_code = "<a href=" + '"' + link + '"' + TARGET_BLANK + '>' + name + "</a>"
482
    if center:
483
        link_code = "<center>" + link_code + "</center>"
484
    file.write(link_code + "\n")
485
    file.write(BREAK_LINE)
486
    if close:
487
        file.close()
488
489
490
def print_adv(file, close=True):
491
    """ Print the advertisement.
492
493
    :param file  : The file that should ad to it.
494
    :param close : Close file after add ad
495
    """
496
    file.write(BREAK_LINE)
497
    file.write(
498
        '<center>' + "<p>" + "Generated " + today_time + " By" + "</p>" + '<a href=' + '"' + HOMEPAGE + '"' + TARGET_BLANK + '>' + '<img src="' + create_badge(
499
            random=True) + '"alt="Qpage">' + '</a> </center>')
500
    if close:
501
        file.close()
502
503
504
def build_index(file):
505
    """ Find and build index page
506
507
    :param file: The index file.
508
    """
509
    image_name = ""
510
    img_format = "jpg"
511
    file_of_images = os.listdir(IMAGE_DIR)
512
    for i in file_of_images:
513
        for form in IMFORMAT_BOX:
514
            if i.find("." + form) != -1:
515
                image_name = os.path.join(IMAGE_DIR, i)
516
                img_format = form
517
                global IMAGE_COUNTER
518
                IMAGE_COUNTER = 1
519
                break
520
    shutil.copyfile(image_name, os.path.join(OUT_DIR, "image." + img_format))
521
    print_image(file, img_format)
522
523
524
def build_resume(file):
525
    """ Find and build resume page.
526
527
    :param file: The resume file.
528
    """
529
    resume_name = ""
530
    file_of_docs = os.listdir(DOC_DIR)
531
    for i in file_of_docs:
532
        if i.find(".pdf") != -1:
533
            resume_name = os.path.join(DOC_DIR, i)
534
            global PDF_COUNTER
535
            PDF_COUNTER = 1
536
            break
537
    shutil.copyfile(resume_name, os.path.join(OUT_DIR, "Resume.pdf"))
538
    print_download(file, "Download Full Version", "Resume.pdf", center=True)
539
540
541
def contain(name):
542
    """main function That Open Each Page HTML File and call other function to write data in it
543
544
    :param name: the name of the file that should be written
545
    """
546
    #
547
    file = open(os.path.join(OUT_DIR, name + ".html"), "a")
548
    text_file = open(os.path.join(DOC_DIR, name + ".txt"), "r")
549
    files.append(file)
550
    files.append(text_file)
551
552
    if name.upper() == "INDEX":
553
        build_index(file)
554
    elif name.upper() == "RESUME":
555
        build_resume(file)
556
557
    print_text(text_file, file)
558
    if name.upper() == "INDEX":
559
        print_adv(file)
560
561
562
def clear_folder(path):
563
    """This Function Get Path Of Foldr And Delete Its Contains
564
565
    :param path: the path that gonna be deleted.
566
    """
567
568
    if os.path.exists(path):
569
        list_of_files = os.listdir(path)
570
        for file in list_of_files:
571
            os.remove(os.path.join(path, file))
572
    else:
573
        os.mkdir(path)
574
575
576
def print_warning():
577
    """ Print Warnings!
578
579
    """
580
    print(str(len(warnings)) + " Warning , 0 Error")
581
    show_items(warnings)
582
583
584
def get_color_code():
585
    """Ask for selecting color of text and background
586
587
    :return list: background and text color
588
    """
589
    for i, item in enumerate(COLOR_BOX):
590
        print(i, "-", item)
591
    back_color_code = int(input("Please enter your background color : "))
592
    if back_color_code not in range(7):
593
        back_color_code = 0
594
    text_color_code = int(input("Please enter your text color : "))
595
    if text_color_code not in range(7):
596
        text_color_code = 1
597
    return [back_color_code, text_color_code]
598
599
600
def color_code_map():
601
    """ Check and insert colors that is chosen.
602
603
    :return list: background and text color
604
    """
605
    [back_color_code, text_color_code] = get_color_code()
606
    if text_color_code == back_color_code:
607
        warnings.append(WARNING_DICT["color_warning"] + " Your text color and background color are same!!")
608
    background_color = COLOR_BOX[back_color_code]  # convert code to color string in COLOR_BOX
609
    text_color = COLOR_BOX[text_color_code]  # convert code to color string in COLOR_BOX
610
    return [background_color, text_color]
611
612
613
def css_font(font_folder):
614
    """ Search and file all fonts.
615
616
    :param font_folder: the folder to search.
617
    :return list : font_flag and the current format
618
    """
619
    font_flag = 0  # 0 If there is no font file in font_folder
620
    current_FONT_FORMAT = None
621
    for i in font_folder:
622
        for j in FONT_FORMAT:  # search for other font format in font box
623
            if i.lower().find(j) != -1:  # If there is a font in font folder
624
                shutil.copyfile(os.path.join(FONT_DIR, i),
625
                                os.path.join(OUT_DIR, "qpage" + j))  # copy font file to output folder
626
                font_flag = 1  # Turn Flag On
627
                current_FONT_FORMAT = j  # font format of current selected font for css editing
628
    return [font_flag, current_FONT_FORMAT]
629
630
631
def font_creator(css_file, font_section):
632
    """ Ask and Select font.
633
634
    :param css_file: the file that font css will be added to.
635
    :param font_section: the font section of css file
636
637
    :return font_section: the font section of css after edit
638
    """
639
    font_folder = os.listdir(FONT_DIR)
640
    details = css_font(font_folder)
641
    current_FONT_FORMAT = details[1]
642
    font_flag = details[0]
643
644
    if font_flag == 1:  # check flag if it is 1
645
        css_file.write(
646
            "@font-face{\nfont-family:qpagefont;\nsrc:url(qpage"
647
            + current_FONT_FORMAT
648
            + ");\n}\n")  # Write font-face in html
649
650
        font_section = "font-family:qpagefont;\n"  # Update Font Section For Body Tag
651
        for i, item in enumerate(FONTSTYLE_BOX):
652
            print(i, "-", item)
653
        font_style = int(input(" Please choose your font style "))
654
        if font_style < len(FONTSTYLE_BOX):
655
            font_style = FONTSTYLE_BOX[font_style]
656
        else:
657
            font_style = "normal"
658
        font_section = font_section + "font-style:" + font_style + ";\n"
659
    else:
660
        warnings.append(WARNING_DICT["font_warning"] + " There is no specific font set for this website!!")
661
    return font_section
662
663
664
def css_creator():
665
    """Ask For background and text color in and make css """
666
    font_section = 'font-family : Georgia , serif;\n'
667
    colors = color_code_map()
668
    background_color = colors[0]
669
    text_color = colors[1]
670
671
    css_file = open(os.path.join(OUT_DIR, "styles.css"), "w")  # open css file
672
    font_section = font_creator(css_file, font_section)
673
674
    css_file.write(
675
        ".body_tag{\n"
676
        + "background-color:"
677
        + background_color
678
        + ";\n"
679
        + font_section
680
        + CSS_MARGIN
681
        + CSS_ANIMATION_1
682
        + "}\n")  # write body tag
683
684
    css_file.write(".color_tag{\n" + "color:" + text_color + ";\n}")  # write color_tag in css
685
    css_file.write(CSS_ANIMATION_2)
686
    css_file.close()  # close css file
687
688
689
def preview():
690
    """Preview website in browser """
691
    # TODO: not working on unix
692
693
    webbrowser.open(os.path.join(OUT_DIR, "index.html"))
694
695
696
def error_finder():
697
    """ Check and find error that display it"""
698
    error_vector = []
699
    pass_vector = []
700
    PDF_COUNTER = 0
701
    # image_list = os.listdir(IMAGE_DIR)
702
    doc_list = os.listdir(DOC_DIR)
703
    if IMAGE_COUNTER == 1:
704
        pass_vector.append("[Pass] Your profile image in OK!!")
705
    else:
706
        error_vector.append(ERROR_DICT["image_error"] + " Your profile image is not in correct format")
707
    if len(doc_list) == 0:
708
        error_vector.append(ERROR_DICT["empty_error"] + "There is no file in doc folder ( index.txt and .pdf file in "
709
                                                        "necessary)")
710
    else:
711
        if "index.txt" in doc_list:
712
            pass_vector.append("[Pass] index.txt file OK!")
713
        else:
714
            error_vector.append(ERROR_DICT["firstpage_error"] + " index.txt is not in doc folder!")
715
        if PDF_COUNTER == 0:
716
            error_vector.append(ERROR_DICT["resume_error"] + "[Error] Where Is Your Resume File? It should be in doc "
717
                                                             "folder")
718
        else:
719
            pass_vector.append("[Pass] Your Resume File is OK!!")
720
    return [error_vector, pass_vector]
721
722
723
def icon_creator():
724
    """ Find .ico file and use it as favicon of website."""
725
    icon_flag = 0
726
    for file in os.listdir(IMAGE_DIR):
727
        if file.endswith('ico'):
728
            shutil.copy(os.path.join(IMAGE_DIR, file), OUT_DIR)
729
            os.rename(os.path.join(OUT_DIR, file), os.path.join(OUT_DIR, 'favicon.ico'))
730
            icon_flag = 1
731
            break
732
    if "favicon.ico" in os.listdir(SOURCE_DIR) and icon_flag == 0:
733
        shutil.copy(os.path.join(SOURCE_DIR, "favicon.ico"), OUT_DIR)
734
        warnings.append(WARNING_DICT["icon_warning"] + " There is no icon for this website")
735
736
737
def robot_maker():
738
    """ Create Robots.txt for pages """
739
    robots = open(os.path.join(OUT_DIR, "robots.txt"), "w")
740
    robots.write("User-agent: *\n")
741
    robots.write("Disallow: ")
742
    robots.close()
743
744
745
def internet(host="8.8.8.8", port=53, timeout=3):
746
    """ Check Internet Connections.
747
748
    :param  host: the host that check connection to
749
    :param  port: port that check connection with
750
    :param  timeout: times that check the connnection
751
752
    :return bool: True if Connection is Stable
753
    """
754
    try:
755
        socket.setdefaulttimeout(timeout)
756
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
757
        return True
758
    except Exception as ex:
759
        error_log(ex)
760
        return False
761
762
763
def server():
764
    """Get Server response."""
765
    # global meta_input
766
    headers = {'content-type': 'application/json', "NAME": meta_input, "VERSION": VERSION, "SYSTEM": system_details(),
767
               "IP": find_global_ip()}
768
    response = requests.get(SERVER_API, headers=headers)
769
    if response.status_code == 200:
770
        print("Installed Saved!")
771
772
773
def version_control():
774
    """ Check and update VERSIONs. """
775
776
    try:
777
        # print("Check for new VERSION . . .")
778
        # print_line(70)
779
        VERSION_pattern = r"last_VERSION:(.+)"
780
        if internet():
781
            response = requests.get("http://www.qpage.ir/releases.html")
782
            body = response.text
783
            last_VERSION = float(re.findall(VERSION_pattern, body)[0][:-3])
784
            if last_VERSION > float(VERSION):
785
                print_line(70)
786
                print("**New VERSION Of Qpage Is Available Now (VERSION " + str(last_VERSION) + ")**")
787
                print("Download Link -->" + "https://github.com/sepandhaghighi/qpage/archive/v" + str(
788
                    last_VERSION) + ".zip")
789
                print_line(70)
790
            else:
791
                # TODO : fix VERSION control else
792
                pass
793
                # print("Already Updated!!!")
794
                # print_line(70)
795
    except Exception as e:
796
        error_log(e)
797
        pass
798
799
800
def enter_to_exit():
801
    """Quit Project by pressing a key.
802
803
    """
804
805
    print_line(70, "*")
806
    response = input("Enter [R] for restart Qpage and any other key to exit : ")
807
    if response.upper() != "R":
808
        sys.exit()
809
810
811
def wait_func(iteration):
812
    """Wait for-in range Iteration.
813
814
    :param iteration: the amount of wait.
815
    """
816
817
    for _ in range(iteration):
818
        time.sleep(1)
819
        print(".")
820