Completed
Push — master ( 43d81b...a05ad4 )
by Sepand
01:32
created

LSM_translate()   B

Complexity

Conditions 6

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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