Completed
Push — master ( 49bd03...055086 )
by Sepand
01:02
created

create_badge()   A

Complexity

Conditions 2

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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