Completed
Push — master ( 506b82...406543 )
by Sepand
50s
created

system_details()   A

Complexity

Conditions 1

Size

Total Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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