Completed
Push — master ( 648d41...e0458e )
by Sepand
53s
created

contain()   A

Complexity

Conditions 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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