Completed
Push — master ( 8ecd75...39a2f9 )
by Sepand
55s
created

name_standard()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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