Completed
Push — master ( 04227d...0cb8d3 )
by Sepand
01:06
created

get_color_code()   B

Complexity

Conditions 4

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

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