Completed
Push — master ( 19d2cd...65d47d )
by Sepand
01:01
created

PAGE_NAME_update()   A

Complexity

Conditions 4

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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