Completed
Push — master ( ee4e60...486148 )
by Sepand
01:02
created

css_creator()   B

Complexity

Conditions 4

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

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