Completed
Push — master ( 932688...a28884 )
by Sepand
01:30
created

sample_site_download()   B

Complexity

Conditions 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

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